简体   繁体   中英

Python: Importing multiple methods from external module

With very common Python modules, I find that importing using the from .. import statement greatly increases the readability of my code, since I can reference methods by name without the dot notation. However, in some modules, the methods I require are nested differently, eg in os :

from os.path import join
from os import listdir, getcwd

Why doesn't from os import path.join, listdir, getcwd work? What would be a "pythonic" way to import all the methods I need in a more succinct manner?

The opinion on whether from <module> import <identifier> is Pythonic itself is quite split - it hides away the origin of a method so it's not easy to figure out whence a certain variable/function comes from just by perusing the code. On the other hand, it reduces verbosity which some people consider Pythonic even tho it's not specifically mandated. Either way, Pythonic is as elusive term as you're going to get and more often than not it means " the way I think Python code should look like " backed up by several PEPs and obscure mail list posts while conveniently omitting the ones that go against one's notion of Pythonic .

from os import path.join doesn't work because os defines the os.path module (by directly writing to sys.modules of all things), it's not an identifier in the os module itself. path , however, is an identifier in the os module pointing to the os.path module so you can do from os import path or from os.path import join .

Finally, succinct and Pythonic are not synonyms, in fact PEP 8 for example prescribes using multiple lines for multiple imports even tho you can succinctly write import <module1>, <module2>, <module3> ... . It says that it's OK to import multiple identifiers like that, tho, but keep in mind that os and os.path are two different modules so based on PEP 8 they shouldn't be on the same line and therefore should be written as:

from os import <identifier_1>, <identifier_2>
from os.path import <identifier_3>, <identifier_4>

Now, I would go as far as claiming that this is Pythonic but it makes the most sense based on PEP 8, at least to me.

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