views:

92

answers:

1

I am trying to understand why any import can be referenced using the importing module, e.g

#module master.py
import slave

and then

>>>import master
>>>print master.slave

gives <module 'slave' from 'C:\Documents and Settings....'>

What is the purpose of the feature? I can see how it can be helpful in a package's __init__.py file, but nothing else. Is it a side effect of the fact that every import is added to the module's namespace and that the module's namespace is visible from the outside? If so, why didn't they make an exception with data imported from other modules (e.g don't show it as part of the module's namespace for other modules)?

A: 

It's a side effect, but it can be used purposefully, e.g. os.py imports either posixpath or ntpath as path in order to create os.path.

Ignacio Vazquez-Abrams
But even in a world where imports weren't automatically visible from the outside, you could've made them visible explicitly, by doing os.path=posixpath, i.e define a variable called path and assign posixpath to it.
noam
@noam: Exactly. The core devs would waste effort making the exception, then somebody who didn't like the wall would climb over it, tunnel under it, or just ride a bicycle around the end of it. Best not to have walls in the first place. Have you actually noticed any detrimental effects from not making the exception?
John Machin
@John Machin: The exact same arguments you state could have been used when the suggestion to obscufate any class member that starts with two underscores was on the table - people can still "tunnel under it" i.e use _ClassName__MemeberName. And I am sure you know the reasoning for the obscufation.And yes, I have one example that is problematic: Usually a module would want to expose to the public only those part of it that are relevant, but here you also expose the module it uses: `os.path='hello world` (why not make it harder for someone to just switch one module's imports like that?)
noam
@noam: If some idiot wants to do os.path = hismodule, that's his problem, his app, his computer. Why should we care? Anyway, this is a forum for people who want help, not for argy-bargy. Just stop worrying, OK?
John Machin
Python doesn't like to restrict you unless it has to. Other languages put up guard rails where Python doesn't. Part of why it's so flexible.
prestomation