Python3 - How do I import a class from another file

Terry Reedy tjreedy at udel.edu
Sun Dec 8 14:47:57 EST 2019


On 12/8/2019 1:29 PM, R.Wieser wrote:


> from the_file import ClassName

from somemod import name

has the same effect as

import somemod
name = somemod.name
del somemod

which is to import a particular 'name' linked to a particular python 
object into the namespace where the import is executed. 
sys.modules['somemod'] will become or continue to be the module 
resulting from executing the 'somemod' code.

>> 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

The entire module is executed the first time it is imported.

> 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.

Not really.  The resulting global objects do not normally take enough 
space to worry about on normal modern desktops.  It is normal for a 
module to only use a subset, possibly just one, of the objects in an 
imported module.  For instance, itertools has 18 public classes but 
almost no importer uses all of them.

>> 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 ...

Standard for in-file test is

def test(): <test code>

if __name__ == '__main__':
     test()

> Question: what is, in python, the convention in naming classes ?

The PEP 8 convention (except for basic builtin data structures like int, 
str, list, tuple, set, and dict) is TitleCase.  Follow or not as you wish.

> Pre- or postfix it with "class" ?

No


-- 
Terry Jan Reedy



More information about the Python-list mailing list