I only know Intra-package import for a few hours after reading someone’s code:
from .version import VERSION
(By the way, the version.py is interesting. Wondering if there is any particular reason to put package version out of __init__.py)
This was first time I saw the syntax and I am pretty sure I never heard of Intra-package import or relative import before. Alright, maybe once or twice. It’s in the Python documentation, but I never had a chance to read about import. I started writing Python script before version 2.5 and never had a problem with importing, an excuse? Perhaps.
PEP 328 lists some proposed syntax, though the final do not include them, but it worth reading. Also read PEP 366.
Basically, you prefix one dot to indicate relative import. One more dot, go up one level. Simply as that.
In PEP 328, I found
from ...package import bar from ...sys import path
do not work, they go beyond the package. The Python documentation does not mention that, so I think it’s not valid since it’s not intra-package.
I think relative import is helpful, because I used to write a code in a package like
from package.subpackage import sibling_module
in a module. With this relative, it looks more clear:
from . import sibling_module
at least to me. Though the first one works well, but if you happen to be in need of change the package name, you know it will be some minutes task, depends on your shell scripting skill or how fast you can search-and-replace with your favorite editor.
I also found one thing I didn’t know before, you can from package import (module1, module2). Well, I don’t know if anyone ever import with that syntax. The only reasonable way I can think of is to format like this:
from package import ( mod1, mod2, mod3, mod4)
Probably put modules into different lines for whatever reason.
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.