class atribute name mangling and exec()

David Bolen db3l at fitlinxx.com
Thu Jul 26 23:01:47 EDT 2001


Tom Harris <tomh at optiscan.com> writes:

> See what I mean? The name mangling is defeated inside the evaluation
> performed by the exec statement. What is the moral here, exec() is evil, or
> name mangling is easily broken, so avoid it (I have a heavy C++ background,
> so hiding everything in classes is a serious obsession)? 

The mangling can only take place when the compiler considers itself to
be parsing that specific class, and exec() compiles its code in a
different context.  There's a paragraph discussing that in the
tutorial, in section 9.6, "Private Variables".  So it's probably a
little of both (easily broken, and exec is evil).  Note that if you
explicitly mangle the name inside of exec it should work fine :-)

But definitely - if you think that using __ is any "hard" protection
against someone poking into your data, you may as well forget it.
Worst case, introspection can just locate the attribute as your dir()
output shows.

Python has some conventions that can make it easier to avoid trampling
ostensibly "private" data in a class or instance, but don't be fooled
that it's any guarantee.  And to be honest, I find that works just
fine.  Code doesn't violate the convention unless it really wants to,
but when it really wants to, being able to is just so very convenient.

--
-- David
-- 
/-----------------------------------------------------------------------\
 \               David Bolen            \   E-mail: db3l at fitlinxx.com  /
  |             FitLinxx, Inc.            \  Phone: (203) 708-5192    |
 /  860 Canal Street, Stamford, CT  06902   \  Fax: (203) 316-5150     \
\-----------------------------------------------------------------------/



More information about the Python-list mailing list