embarrassing class question

Brendan brendandetracey at yahoo.com
Fri Oct 22 16:49:39 CEST 2010


On Oct 22, 9:16 am, Dave Angel <da... at dejaviewphoto.com> wrote:
> On 2:59 PM, Brendan wrote:> On Oct 21, 3:56 pm, Ethan Furman<et... at stoneleaf.us>  wrote:
> >> <snip>
> >> 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.
>
> Since you make the common mistake of using the same name for the module
> as you do for the class, it's hard to demonstrate.  But if you used Pep8
> naming conventions, the classes would be capitalized.
>
> Instead of using
>
> from x import X
>
> try using
>
> import x
>
> class Y(x.X):
>      pass
>
> Now, you still have a symbol x in your namespace, but it's just the
> module, which is perfectly public.  So you could access a dozen classes
> within x, but only the module itself would be visible to others.
>
> As someone else pointed out, you could also delete the module reference
> when you're done with it.
>
> import x
>
> class Y(x.X):
>      pass
>
> del x
>
> DaveA

x.py
class X(object):
    pass

y.py
import x
class Y(x.X):
    pass

z.py
import x
import y
class ZX(x.X):
    pass
class ZY(y.Y):
    pass

w.py
import x
import y
import z
class WX(x.X):
    pass
class WY(y.Y):
    pass
class WZX(z.ZX):
    pass
class WZY(z.ZY):
    pass

>>> import x, y, z, w
>>> dir(x)
['X', '__builtins__', '__doc__', '__file__', '__name__',
'__package__']
>>> dir(y)
['Y', '__builtins__', '__doc__', '__file__', '__name__',
'__package__', 'x']
>>> dir(z)
['ZX', 'ZY', '__builtins__', '__doc__', '__file__', '__name__',
'__package__', 'x', 'y']
>>> dir(w)
['WX', 'WY', 'WZX', 'WZY', '__builtins__', '__doc__', '__file__',
'__name__', '__package__', 'x', 'y', 'z']



More information about the Python-list mailing list