简体   繁体   中英

Python module best practices

Let's say I have a simple module ( foo.py ) like so:

import os
import sys

THIS_IS_A_CONSTANT = sys.path

def this_is_a_function():
    print os.name()

Now, suppose this that I import foo . I would now have the following:

>>> dir(foo)
['THIS_IS_A_CONSTANT', '__builtins__', '__doc__', '__file__', '__name__', '__package__', 'os', 'sys', 'this_is_a_function']

To me, it is distracting and annoying that I can access foo.os and foo.sys because IMO they shouldn't be exported by module foo .

I could add del sys to the end of foo.py , but is this considered bad practice? Unfortunately, the same cannot be done for del os .

如果确实困扰您, import sys as _sys ,依此类推。

It's good this way. Otherwise, you could have long modules that rely on lots of imports and not keep track of all the imports needed in the main function. I don't really see any issues with foo.py exporting sys and os .

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