detmining name during an assignment

Jamie Riotto jamie.riotto at gmail.com
Sat Sep 19 00:57:41 CEST 2009


On Fri, Sep 18, 2009 at 1:10 PM, Gabriel Genellina
<gagsl-py2 at yahoo.com.ar> wrote:
> En Fri, 18 Sep 2009 14:38:08 -0300, Christian Heimes <lists at cheimes.de>
> escribió:
>>
>> Jamie Riotto schrieb:
>
>>> I have an app that uses Python scripting. When a user creates a new
>>> object:
>>>
>>> objName = newObject()
>>>
>>> I'd like the newObject be able to use objName as its internal name.
>>
>> As the others already explained to you there is no way to archive your
>> goal with an assignment to a local or global variable. But you can
>> follow a different approach:
>>
>> class Scene(object):
>>    def __setattr__(self, name, value):
>>        super(Scene, self).__setattr__(name value)
>>        if isinstance(value, SceneObject):
>>            value.name = name
>>            value.scene = self
>>
>> class SceneObject(object):
>>    pass
>>
>> class Cube(SceneObject):
>>    pass
>>
>> scene = Scene()
>> scene.cube1 = Cube()
>
> As the OP said it's being used for scripting some application, presumably
> the application can control the environment on which the script is run. One
> may use the Scene class above as the globlal scope when executing the
> script:
>
> scene = Scene()
> code = "cube1 = Cube(); print cube1.name"
> exec code in Scene
>
> (well, not exactly, Scene should inherit from dict and override __setitem__
> instead, but you get the idea)
>
> --
> Gabriel Genellina
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>

Thanks for the detailed clarifications and suggestions. I understand
the problem a lot better now.
However, I'll have to keep looking for a more elegant solution.
Telling a user that typing:
cube1 = Cube(name = cube1) is a good thing because its pythonic is
somehow unsatisfying.

Also, in the last suggestion about execution the script in the Scene
Handler global scope, well thats
exactly what I do, and yes, cube1=Cube, print cube1.name works great.
The issue is say perhaps that
cube then collides with something called sphere1. How does cube1 know
that it hit "sphere1" and not
just a sphere object. Since I can execute the scripts one line at a
time, I suppose I could search dictionaries
for new names pointing to the same object after every execution, but Yuck.

Perhaps the best approach is a preprossesor that looks for lines of
the form "name = class()" and adds in the
class(name = name) behind the scenes. Thanks again - jamie



More information about the Python-list mailing list