Python3 - How do I import a class from another file

Peter Otten __peter__ at web.de
Sun Dec 8 11:59:02 EST 2019


R.Wieser wrote:

> Hello all,
> 
> Using Python3 I would like to import a specific class from another file
> (in the same folder), and have trouble doing so.
> 
> "from file import function" works, but fails when I try to do the same
> with a class.

Are you sure? It should behave the same for any name in the module.
 
> "import file
> x = file.class"
> 
> works, but also executes commands that are in the root of the file. And
> ofcourse loads all of the file, not just the class that I'm after ...
> 
> In other words, what is the syntaxt I should use ?

The body of a module that is imported is always executed -- that's how the 
classes and functions (and everything else) in the module are created.
It's all or nothing, you cannot cherry-pick specific classes or functions.

You can however protect part of the code with 
'if __name__ == "__main__": ...':


print("this will always be executed")
if __name__ == "__main__":
   print("this will only be executed when you run")
   print("the module directly as a script")




More information about the Python-list mailing list