Python introspection and namespace weird question
Rayene Ben Rayana
rayene.benrayana at gmail.com
Mon Dec 1 21:23:10 CET 2008
Yeah it is kinda meta thing. My app allows to create a scene (a set of GUI
objects). A scene can be saved as a python script. And, it can be loaded
again using execfile().
each GUI object has a label. So, in the script scene, declaring an object in
a scene file should look like this:
red_car = MyVehicleClass(*label* = 'red_car')
But, I wanted to simplify the syntax of scene files and avoid repetition so
it would look like
red_car = MyVehicleClass()
with the *label* attribute automatically set to the name of the
I tried your locals().iteritems tip and it works perfectly.
The question now is: Given what I just explained, do you still think it is
bad programming to do that ? Should I better use the first syntax ?
I want to use that to simplify the syntax of the
On Mon, Dec 1, 2008 at 7:37 PM, Chris Rebert <clp at rebertia.com> wrote:
> On Mon, Dec 1, 2008 at 6:04 AM, Rayene Ben Rayana
> <rayene.benrayana at gmail.com> wrote:
> > Hello everybody,
> > Is there an easy way to do something like this in python ?
> >>>> red_car = MyVehicleClass()
> >>>> car = red_car
> >>>> car.labels()
> > ['red_car' , 'car' ]
> > In other words, does an instance has access to its name pointers ?
> In short, No. (Cue another debate over whether Python uses call-by-X
> Typically people who want to do such things actually want/should use a
> dictionary mapping string keys to instance values instead.
> Note that in certain limited cases, voodoo involving the locals() or
> globals() built-in functions or the `inspect` module can work, but not
> in the common general case. But generally these techniques are
> considered bad style and kludgey unless you're writing a debugger or
> something equally meta, with using a dictionary as explained
> previously being much preferred.
> For example, for your particular code above, the following happens to work:
> [name for name, obj in locals().iteritems() if obj is car] #==>
> ['red_car' , 'car' ]
> But this will only give the names in the current function of the
> particular car object. Likewise, globals() works only for module-level
> names, and the `inspect` module's magic only works for names in
> calling functions (i.e. those below the current one in the callstack).
> Follow the path of the Iguana...
> > Thanks in advance,
> > Rayene
> > --
> > http://mail.python.org/mailman/listinfo/python-list
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Python-list