2

Why doesn't the decorated method doesn't show up in NextTip(Pycharm)

from functools import wraps

def add_method(cls):
    def decorator(func):
        @wraps(func)
        def wrapper(self, *args, **kwargs):
            return func(self, *args, **kwargs)
        setattr(cls, func.__name__, wrapper)
        return func
    return decorator
class Apple():
    def __init__(self):
        print("my apple")
    def appletest(self):
        print("apple test")
@add_method(Apple)
def mangotest(self):
    print("mango test")
a = Apple()
a.appletest()
a.mangotest()

Output is fine,

my apple apple test mango test

Once I type a. I can see appletest but not mangotest as my tip. How can i achieve it in my editor ?

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
rajdallas
  • 65
  • 1
  • 4

1 Answers1

1

The additional method only gets added to the class at runtime because of how you set that up. PyCharm doesn't run your code constantly to see what methods every class have just to give you good hints.

This is also true of any other IDE I'm familiar with.

The extent to which your IDE know about methods and properties of classes and instances is almost never outside of what is coded in the actual class (and any parent class).

You can test it even without a wrapper or decorator. Have this command by itself after the class definition (or even inside the __init__ method):

setattr(Apple, 'test', 'test')

And you'll never get a hint when trying to write Apple.test, even though that attribute is there and will return the 'test' value correctly

Ofer Sadan
  • 11,391
  • 5
  • 38
  • 62
  • thanks Ofer. If I define a class as separate .py(mark it as resources root) or import it. Is it possible to achieve what i expect ? I – rajdallas Nov 17 '19 at 01:39
  • You can try, but I doubt it. I think the same process is implemented for imported code – Ofer Sadan Nov 17 '19 at 04:14