Python importer with alias

I am new to Python 3 and am currently learning how to create Python modules. I created below package structure.

maindir
    test.py
    package
        __init__.py
        subpackage
            __init__.py
            module.py

      

This is my module.py file

name="John"
age=21

      

and this is my test.py file

import package.subpackage.module
print(module.name)

      

When I run test.py I get this error NameError: name 'module' is not defined

However, when I change the import statement to import package.subpackage.module as mymod

and print the name with print(mymod.name)

, then it works as expected. His typing name is John. I didn't understand why it works with the second case and not the first.

+3


source to share


2 answers


You may have tried this:

from package.subpackage import module

      

Then you can refer to module

as a name afterwards.



If you do:

import package.subpackage.module

      

Then your module will be named exactly package.subpackage.module

.

+2


source


With a little reading, I figured out this behavior now. Please correct me if I am wrong.

With this import package.subpackage.module

style of import operation, you must access objects with their fully qualified names. For example, in this case print(package.subpackage.module.name)



With anti-aliasing, I can shorten the long name import package.subpackage.module as mymod

and print directly withprint(mymod.name)

In short print(package.subpackage.module.name)

==print(mymod.name)

0


source







All Articles