embarrassing class question
Robert Kern
robert.kern at gmail.com
Thu Oct 21 15:41:37 EDT 2010
On 10/21/10 2:12 PM, Brendan wrote:
> On Oct 21, 3:56 pm, Ethan Furman<et... at stoneleaf.us> wrote:
>> Jonas H. wrote:
>>> On 10/21/2010 08:09 PM, Brendan wrote:
>>>> Two modules:
>>>> x.py:
>>>> class x(object):
>>>> pass
>>
>>>> y.py:
>>>> from x import x
>>>> class y(x):
>>>> pass
>>
>>>> Now from the python command line:
>>>>>>> import y
>>>>>>> dir(y)
>>>> ['__builtins__', '__doc__', '__file__', '__name__', '__package__',
>>>> 'x', 'y']
>>
>>>> I do not understand why class 'x' shows up here.
>>
>>> Because that's how `import` behaves. It imports *every* member of the
>>> module into the importing module's global namespace (except for
>>> attributes that start with an underscore).
>>
>> Um, no. (unless you do "from<whatever> import *" at the module level)
>>
>> What it does is add whatever you imported into the namespace where you
>> imported it.
>>
>> Because y.py has "from x import x" the x class from x.py is added to the
>> y.py namespace.
>>
>> ~Ethan~- Hide quoted text -
>>
>> - Show quoted text -
>
> So what is usually done to prevent this? (In my case not wanting class
> x added to the y.py namespace)
> It seems sloppy.
You can explicitly delete it at the end of the file if you never reference it
from one of your methods.
Mostly though, it just doesn't matter much. I recommend leaving it alone. If you
want a nice, clean namespace for people to use, make a module (e.g. api.py) that
doesn't define any classes or functions but just imports them from their
defining modules.
--
Robert Kern
"I have come to believe that the whole world is an enigma, a harmless enigma
that is made terrible by our own mad attempt to interpret it as though it had
an underlying truth."
-- Umberto Eco
More information about the Python-list
mailing list