简体   繁体   中英

Python import module approaches

I have created a package named mod and placed a python file inside it (aka: 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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM