0

I want add a method to a class, without extending another class (for the import statements should be unaltered).

Conceptually, my current approach is:

add_method.py

def new_method():
    pass

MyObject.new_method = new_method

main.py

from package import MyObject
import add_method

ob = MyObject()
ob.new_method()

This does the job, however, PyCharm does not recognize that the import add_method import statement is acutally used: "Unused import statement". Is there an elegant way to obtain the same effect with PyCharm recognizing the import?

Simon
  • 5,464
  • 6
  • 49
  • 85
  • 1
    You dont' use `add_method` in your code, hence the `Unused import statement`. What else were you expecting? – Devesh Kumar Singh May 24 '19 at 13:26
  • Without importing `add_method`, MyObject will not have the `new_method`. Of course, there are other programming patterns to add the `new_method` to the MyObject class, however this one has the advantage of allowing extending existing objects without altering the class definition code. – Simon May 24 '19 at 13:31
  • 3
    It is very unexpected and in fact not reliable to have a package import have side effects like this. When doing `import foo`, you don't expect `foo` to impact another module `bar`, and you should use `foo` directly in some way in the module where it's imported. At least do some sort of decorator which you need to explicitly apply, like `foo.augment(MyObject)`. – deceze May 24 '19 at 13:34

0 Answers0