Search code examples
pythonclassmethodsconventions

Can I include Python implementation of class method saved in another file


In Python, we cannot save class method's definition outside of class definition itself (as I understand it) because there is no concept of declaration. However, I wonder whether it is possible that I can include source code of method implementation saved in a standalone file, namely having the interpreter replace the piece of code in question. But as I have never seen such thing, this is probably not idiomatic in Python. Then how do you deal with the irritation that a class definition will be extremely long? Please correct me since I am new to Python, and find it quite different from C++.

class Foo
   def bar():
      # How to include definition saved in another file?

Solution

  • Can do!

    First solution

    bar.py

    def bar(foo):
        print foo
    

    foo.py

    from bar import bar as foo_bar
    
    class Foo:
        bar = foo_bar
    

    Alternative solution

    bar.py

    def bar(foo):
        print foo
    

    foo.py

    from bar import bar as foo_bar
    
    class Foo:
        def bar(self, *args, **kwargs):
            return foo_bar(self, *args, **kwargs)