3

I am newbie to Python 3 and currently learning how to create Python modules. I have 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 am getting 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 its working as expected. Its printing name John. I didn't understand why its working with second case and not with first.

3
  • Use print(package.subpackage.module.name). module alone is not in the current scope. Commented May 16, 2015 at 12:00
  • Then how import sys print(sys.path) works? Commented May 16, 2015 at 12:06
  • @vivekratnaparkhi that is because sys is an imported name. when you import package.subpackage.module, you import the name package.subpackage.module, not module Commented May 16, 2015 at 12:20

2 Answers 2

3

Perhaps what you were attempting was this:

from package.subpackage import module

Then you can reference module as a name afterwards.

If you do:

import package.subpackage.module

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

Sign up to request clarification or add additional context in comments.

1 Comment

I want to understand the behaviour of this style of import import package.subpackage.module. I still understand the behaviour.
0

With little bit of reading I understood this behaviour now. Please correct me If I am wrong.

With this import package.subpackage.module style of import statement you have to access the objects with their fully qualified names. For example, in this case print(package.subpackage.module.name)

With aliasing I can shorten the long name with import package.subpackage.module as mymod and print directly with print(mymod.name)

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

1 Comment

you can also import the short name as above: from package.subpackage import module then print(module.name)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.