Python3 - How do I import a class from another file

Python python at python.invalid
Sun Dec 8 11:45:36 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.
> 
> "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 ...

from the_file import ClassName

should work. I guess that your class name is not "class" right?

Note that in all cases when you import a module (either by
import the_file or from the_file importe whatever) you actually
import ALL of it (even if you don't see ALL names your name
space). If you do not want part of a module to be executed when
it is imported (any ways) but only when the file is executed
as a script (i.e. python3 the_file.py or ./the_file.py) then
you can test the name __name__ : it is a string "__main__"
when it is executed and the module name when imported :

if __name__ == '__main__':
     # not run when imported
     print("Hello world!")



More information about the Python-list mailing list