Python3 - How do I import a class from another file

R.Wieser address at not.available
Sun Dec 8 13:29:24 EST 2019


Python,

> from the_file import ClassName
>
> should work. I guess that your class name is not "class" right?

You guessed that right. :-)   Not a good idea to pick confusing names like
that, especially when you do something the first time.

> 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

So much for my assumption only the class itself would be loaded - and a
wrench into my idea to have a number of classes in a "library" file.

And it turns out its also the cause of my problem: The displayed error told
me that it could not import the class from the file, but when I block-quoted
the testcode (instanciating the class, calling it and deleting the instance
afterwards) it all worked as it should.   No idea why though.

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

Thanks for that.  It means I do not have to block-quote the testcode every
time - which I'm certain I will forget now-and-again ...

Update: While testing a bit more it turned out that, in the testcode, my 
creating an instance with the same name as the class is to blame (who again 
said that it isn't a good idea to use confusing names ?).  The moment I 
changed the name of the instance everything works as expected.

Question: what is, in python, the convention in naming classes ?   Pre- or 
postfix it with "class" ?  Something else ?

Regards,
Rudy Wieser





More information about the Python-list mailing list