Search code examples
pythonpython-importpython-module

Import from file without executing imports at the top of that file


I have one file, foo.py

import UnavailableModule

class Bob:
    def useful_func(self, arg):
        # Do useful stuff (doesn't use UnavailableModule)

And in another file bar.py in the same directory, I need useful_func() but can't do this

from foo.Bob import useful_func

because it results in

problem: [Error 126] The specified module could not be found
An exception has occurred, use %tb to see the full traceback.

with traceback

C:\...\bar.py in <module>()
----> 1 from foo.Bob import useful_func
C:\...\foo.py in <module>()
----> 1 import UnavailableModule

Is it possible to just get useful_func() only by some other means?


Solution

  • First of all your useful_func is an instance method, you can import it with whole Bob class, like this :

    from foo import Bob
    

    then you can create object of Bob and use your function like this:

    b = Bob()
    b.useful_func('something useful i believe')
    

    but this does not solve your problem. Your problem as I read is that import of UnavailableModule is run while importing foo module.

    Well, it will be run, because that is how imports work, you can prevent this import with such construct:

    class Bob:
      def useful_func(self, arg):
          pass
    
    if __name__ == '__main__':
      import UnavailableModule
    

    This will prevent importing your UnavailableModule while importing foo module from another module. However I am not sure whether this is good practice. It works though.