0

I have created a package named mod and placed a python file inside it (a.k.a: module). The name of the python file is printme.py.

I import the module in the below couple of ways.

import mod.printme 

 ['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'mod']

After this is executed, the name space is appended with the value mod. I expected this to have the value printme (which is the actual module name)

from mod import printme

['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'printme']

After this is executed, correctly the name space is appended with the value printme as expected.

Technically, both are expected to import the module printme in the local namespace, I am little puzzled why the first approach is NOT placing the printme module name in the local namespace.

Could someone please help me to understand.

Thanks!

1
  • 2
    in the first version you have to all a function in your module as mod.printme.function() - therefore mod needs to be accessible to python. in the second versioun you would call printme.function() - here only the name printme must be defined. Commented Jan 5, 2023 at 7:49

1 Answer 1

1

Assume mod to be a book and printme.py as a chapter.

When you are commanding that import mod.printme you are saying to python "Hey! Please bring mod book and it's printme chapter as a whole book and remove other chapters". Now whenever you need to reference content from this book you need to say mod.printme.foo() as the name of your new book is mod and it has only one chapter printme.

When you are commanding that from mod import printme you are saying: "Hey! Please bring print me chapter in mod book as a book in itself". Now whenever you need to reference content from this book you need to say printme.foo() as the chapter has become book so only name of book, in your case printme, is needed.

And if you want Python to bring all headings of chapter printme in your current book (the book you are writing, as in Python each file is a module) you may use from mod.printme import *. It will bring all headings only. So you need not to reference the book/chapter, just foo() will work.

They works this way because they are made to work this way.

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

2 Comments

However, do not use from mod.printme import * as it will make namespace a mess. Instead use from mod.printme import foo
It is nice analogy to understand the concept in a much better way. Thanks for taking your time to look into the question.

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.