1

Considering the following:

class test:
    att = 7


def print_class(class_instance):
    print(class_instance.att)


if (__name__ == '__main__'):
    t = test()
    print_class (t)

print_class expects a class test instance as a parameter, but this is not typed.

Now I'd like to rename by refactoring att However,

print(class_instance.att)

will not be renamed, as the editor has no clue this is the same attribute. This will be discovered only at run time.

Is there a way to overcome this?

OJNSim
  • 736
  • 1
  • 6
  • 22
  • 1
    You could use type hints, either as annotations or in docstrings, to tell PyCharm what you're expecting: https://www.jetbrains.com/help/pycharm/type-hinting-in-product.html – jonrsharpe May 14 '18 at 11:26
  • @jonrsharpe even a docstring will suffice in this case – DeepSpace May 14 '18 at 11:32
  • @DeepSpace docstrings are a *kind* of type hints, per both my comment and the docs I linked to. – jonrsharpe May 15 '18 at 07:40
  • @jonrsharpe . Not sure I fully understand, type hints, on all forms, are used by the editor, for coding purposes. They are not used by the interpreter. am I right? – OJNSim May 15 '18 at 11:21
  • it is weird that the refactor works when it is a method, but it doesn't work for attributes. Do you @jonrsharpe know why? – Homero Esmeraldo Aug 21 '18 at 18:40

1 Answers1

0

As @jonsharpe suggested in the comments, type hints will solve this issue.

However, if you don't want to use type hints, you can use a docstring that attaches a type to class_instance:

class test:
    att = 7


def print_class(class_instance):
    """

    :param test class_instance:
    #       ^ specify type here
    :return:
    """
    print(class_instance.att)


if (__name__ == '__main__'):
    t = test()
    print_class(t)

After refactoring:

class test:
    attribute = 7


def print_class(class_instance):
    """

    :param test class_instance:
    :return:
    """
    print(class_instance.attribute)


if (__name__ == '__main__'):
    t = test()
    print_class(t)
DeepSpace
  • 78,697
  • 11
  • 109
  • 154
  • I was not aware of that. Not sure I fully understand, type hints, on all it's forms, is used by the editor, for coding purposes. am I right? – OJNSim May 14 '18 at 22:15
  • Interesting, but this does not solve the problem if I have usages in many functions. It would take a lot of time to do this in all of them. And also is annoying to have to add docstrings even to very simple functions. – Homero Esmeraldo Aug 21 '18 at 17:59
  • I edited the question to include how to use typehints, which is less verbose than docstrings, but still requires to do it in every usage. – Homero Esmeraldo Aug 21 '18 at 18:27