Python3 - How do I import a class from another file

DL Neil PythonList at DancesWithMice.info
Sun Dec 8 16:30:19 EST 2019


On 9/12/19 7:29 AM, R.Wieser wrote:
...

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

There are three separate ideas which may be confusing:
1 we can 'load' a single class from a module, and
2 we can have 'library files' ("modules") which contains more than one 
importable-object
3 when a module is imported, parts of it are/may be executed at import-time

...

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

and then there are the concepts of "scope" and "namespace".


Some of this you will know. (Hopefully) some will be 'new':


import moduleNM

- imports the entire contents of the module and executes what can be. 
This means that functions and classes are defined, and any executable 
code in the 'mainline', eg print( "Hello World" ); will be run.
- from that time you may then refer to the objects detailed within the 
module, eg

	a = moduleNM.ClassA()

- note how the module has become part of the program, but occupies a 
separate "namespace"


from moduleNM import ClassA

- changes things so that you may now refer to ClassA without mention of 
the moduleNM, ie brings the name "ClassA" into the current namespace
- causes confusion if there is already a ClassA in the current namespace!


from moduleNM import ClassA as ClassA2

- also obviates the need to mention moduleNM/adds to the current namespace
- allows use of both ClassA-s - the 'local' ClassA as "ClassA", as well 
as providing an alias ("ClassA2") to the ClassA defined in moduleNM


import moduleNM as aliasNM; is also available!


WebRefs:
A comfortably readable expansion of the above: 
https://www.digitalocean.com/community/tutorials/how-to-import-modules-in-python-3
Python's view of (import-able) modules: 
https://docs.python.org/3/tutorial/modules.html
Other questions answered: 
https://docs.python.org/3/faq/programming.html?highlight=import, eg 
what-are-the-best-practices-for-using-import-in-a-module
The importlib library which under-pins "import": 
https://docs.python.org/3/reference/import.html
The full-fat range of import-possibilities: 
https://docs.python.org/3/library/modules.html--
Regards =dn


More information about the Python-list mailing list