Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import part of a module in python?

I need to use a python module (available in some library). The module looks like this:

class A:
  def f1():
  ...

print "Done"
...

I need only the functionality of class A. However, when I import the module, the code at bottom (print and others) gets executed. Is there a way to avoid that? Essentially I need to import part of a module: "from module1 import A" which should import only A. Is it possible?

like image 336
amit Avatar asked Dec 13 '22 17:12

amit


1 Answers

Yes, sure:

from module1 import A

Is the general syntax. For example:

from datetime import timedelta

The code at the bottom should be protected from running at import time by being wrapped like so:

if __name__ == "__main__":
  # Put code that should only run when the module
  # is used as a stand-alone program, here.
  # It will not run when the module is imported.
like image 52
unwind Avatar answered Jan 02 '23 08:01

unwind