Thanks Chris, 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 corresponding variable. 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 ? Cheers, Rayene, I want to use that to simplify the syntax of the On Mon, Dec 1, 2008 at 7:37 PM, Chris Rebert <[EMAIL PROTECTED]> wrote: > On Mon, Dec 1, 2008 at 6:04 AM, Rayene Ben Rayana > <[EMAIL PROTECTED]> 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 > semantics...) > > 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). > > Cheers, > Chris > -- > Follow the path of the Iguana... > http://rebertia.com > > > > > Thanks in advance, > > > > Rayene > > > > > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > > >
-- http://mail.python.org/mailman/listinfo/python-list