PyWart: Import resolution order

Rick Johnson rantingrickjohnson at gmail.com
Sat Jan 12 00:28:49 EST 2013


On Friday, January 11, 2013 12:30:27 AM UTC-6, Chris Angelico wrote:
> Why is it better to import from the current directory first?

Opps. I was not explicit enough with my explanation :). I meant, "look in the current directory FIRST when in a package". Since many times (most all times) packages will contain many sub-modules that need to be imported into the package's main.py module, and sometimes these modules will have the same name as a stdlib module, then looking in the package FIRST makes sense.


But the real solution is not to change the default resolution order. The real solution is to wrap all builtin modules into a package and use full paths to access every module. But wait, i have an even better idea... read below!

> Windows
> has that policy for executable commands; Unix, on the other hand,
> requires that you put an explicit path for anything that isn't in the
> standard search path. Which of these options is the more likely to
> produce security holes and/or unexpected behaviour?

I prefer the latter of course :). 

I think if python where *strict* about full paths for non-builtins, then we would be in a better place. But there is an even better solution! Force all python users to wrap THEIR modules in a toplevel package. Maybe even create the package for them. YES!. Call it "lib". Any "naked" modules (meaning modules that are not in a package)  would have to be accessed starting from "lib". Of course professionals like you and i are already using packages to properly nest out modules, but the newbie's won't realize the power of packaging modules for some time, so create the default "lib" package for them.

For instance you could create a package named "chris" and then have a module named math exist inside. Alternatively if you choose to be a non-professional and create a math module without a containing package, python would throw the module into the default "lib" package. The only way you could access your math module now would be by using the path "lib.math". 

So the conclusion is:

 * We encourage python programmers to use packages so they avoid any name clashes with built-in modules. 
 
 * if they refuse fine, any "naked" modules they create will be packaged in a default package (call it "lib", "userlib", or whatever) and will require them to prefix the module name with "lib." -- or "lib:" if i get my way!
 
By doing this we solve the many problems related to module name resolution orders and we create cleaner code bases. Damn i am full of good ideas!

> Welcome back to the list, Rick. Got any demonstrable code
> for Python 4000 yet?

I am working on it. Stay tuned. Rick is going to rock your little programming world /very/ soon.



More information about the Python-list mailing list