473,836 Members | 2,068 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

finding name of instances created

Short version of what I am looking for:

Given a class "public_cla ss" which is instantiated a few times e.g.

a = public_class()
b = public_class()
c = public_class()

I would like to find out the name of the instances so that I could
create a list of them e.g.
['a', 'b', 'c']

I've read the Python Cookbook, Python in a Nutshell, Programming
Python, Learning Python, ... googled (probably missed something
obvious), all to no avail.

=====
Longer version:

If I can do the above, I believe I could do the following thing which
is what I am really after eventually.

Given the statement
a = public_class()
I would like to generate
my_dict['a'] = private_class()
so that one could write
a.apparently_si mple_method()
and that, behind the scene, I could translate that as
my_dict['a'].not_so_simple_ method()
as well as do things like
for name in my_dict:
do_stuff(name)


Any help, pointers, sketches or outline of solution would be greatly
appreciated.

André

Jul 18 '05 #1
21 1772
On Fri, 2005-01-21 at 16:13 -0800, André wrote:
Short version of what I am looking for:

Given a class "public_cla ss" which is instantiated a few times e.g.

a = public_class()
b = public_class()
c = public_class()

I would like to find out the name of the instances so that I could
create a list of them e.g.
['a', 'b', 'c']

I've read the Python Cookbook, Python in a Nutshell, Programming
Python, Learning Python, ... googled (probably missed something
obvious), all to no avail.
Yep. The short answer is that the instances don't have names - they're
just bound to names in a particular scope. They can be bound to
different names in the same scope or in other scopes.

You can get a dictionary for a particular scope using locals() then
search it to find the key for a given value. That key will be the name
the object is bound to in that scope.

In general, you won't want to do that - the need to do so probably
suggests a design issue in what you're trying to do.
If I can do the above, I believe I could do the following thing which
is what I am really after eventually.

Given the statement
a = public_class()
I would like to generate
my_dict['a'] = private_class()
so that one could write
a.apparently_si mple_method()
and that, behind the scene, I could translate that as
my_dict['a'].not_so_simple_ method()

I'm not clear as to why you can't do this as part of the class of which
'a' is an instance.
as well as do things like
for name in my_dict:
do_stuff(name)


Any help, pointers, sketches or outline of solution would be greatly
appreciated.


I'm not really able to grasp what you're trying to do (but others
might). It wouldn't hurt if you could post a description of what you're
actually trying to achieve - /why/ you want this - as that can often be
very helpful both in understanding what you're thinking and in
suggesting a suitable approach or alternative.

--
Craig Ringer

Jul 18 '05 #2
André wrote:
Given the statement
a = public_class()
I would like to generate
my_dict['a'] = private_class()
so that one could write
a.apparently _simple_method( )
and that, behind the scene, I could translate that as
my_dict['a'].not_so_simple_ method()
as well as do things like
for name in my_dict:
do_stuff(name)


Why can't you just make public_class a factory, alias the method in
PrivateClass and access the names through locals()?

py> class PrivateClass(ob ject):
.... def not_so_simple_m ethod(self):
.... print "not so simple"
.... apparently_simp le_method = not_so_simple_m ethod
....
py> def public_class():
.... return PrivateClass()
....
py> a = public_class()
py> a.apparently_si mple_method()
not so simple
py> # add 'name' and 'value' to locals() before iteration starts
py> name, value = None, None
py> for name, value in locals().iterit ems():
.... if isinstance(valu e, PrivateClass):
.... print name, value
....
a <__main__.Priva teClass object at 0x01146D50>

Steve
Jul 18 '05 #3
Craig Ringer wrote:
On Fri, 2005-01-21 at 16:13 -0800, André wrote:
Short version of what I am looking for:

Given a class "public_cla ss" which is instantiated a few times e.g.

a = public_class()
b = public_class()
c = public_class()

I would like to find out the name of the instances so that I could
create a list of them e.g.
['a', 'b', 'c']
[snip]

I'm not really able to grasp what you're trying to do (but others
might). It wouldn't hurt if you could post a description of what you're
actually trying to achieve - /why/ you want this - as that can often be
very helpful both in understanding what you're thinking and in
suggesting a suitable approach or alternative.


Ok, here it goes... I am designing a "learning environment" for Python.
(See rur-ple.sourceforge .org for details of a *very early, still buggy*
relase). I have a "world" in which a
"robot" can accomplish four built-in instructions: move(), turn_left(),
pick_beeper(), put_beeper().
turn_left() corresponds to a 90 degree left turn. One can define a
function to simulate a 90 degree right turn as follows:

def turn_right():
turn_left()
turn_left()
turn_left()

and call it as a built-in instruction thereafter.

By giving more and more complicated tasks for the robot to accomplish,
one can learn various programming concepts using python syntax:
def (as above), while, if, else, elif, ......

I have all of that working well so far (not on sourceforge yet).
Next, I want to introduce
the concept of classes and objects, again using python's syntax.

Behind the scene, I have something like:
robot_dict = { 'robot' = CreateRobot( ..., name = 'robot') }
and have mapped move() to correspond to
robot_dict['robot'].move()
(which does lots of stuff behind the scene.)

I have tested robot_dict[] with more than one robot (each with
its own unique name) and am now at the point where I would like
to have the ability to interpret something like:

alex = CreateRobot()
anna = CreateRobot()

alex.move()
anna.move()

etc. Since I want the user to learn Python's syntax, I don't
want to require him/her to write
alex = CreateRobot(nam e = 'alex')
to then be able to do
alex.move()

I have tried various things at the interpreter, found that
to a class 'a', I could see the instance 'b' created in
locals():
'a': <class '__main__.a'>, 'b': <__main__.a object at 0x011515D0>
which tells me that there must be a way to catch b's name as it is
created, and do what I want to do.

Does this clarify what I am trying to do and why?

André

Jul 18 '05 #4
Using the method suggested by Steven Bethard, I *almost* got it working
the way I would like.
Here's my program:
===
..class PrivateClass(ob ject):
.. dict = {}
.. def not_so_simple_m ethod(self):
.. for name in PrivateClass.di ct.keys():
.. if PrivateClass.di ct[name] == self:
.. print "instance " + name + " called not so simple"
.. apparently_simp le_method = not_so_simple_m ethod

.. def __init__(self):
.. print "instance created"
.. for name, value in globals().iteri tems():
.. if isinstance(valu e, PrivateClass):
.. PrivateClass.di ct[name] = value

..def public_class():
.. return PrivateClass()

..print "=== start==="
..alpha = public_class()
..print "created alpha"
..print PrivateClass.di ct
..print "### alpha is not there\n"

..beta = public_class()
..print "created beta"
..print PrivateClass.di ct
..print "### we are always one behind in the dict content\n"

..alpha.apparen tly_simple_meth od()
..beta.apparent ly_simple_metho d()
=============== =============== ===
The output follows:
=== start===
instance created
created alpha
{}
### alpha is not there

instance created
created beta
{'alpha': <__main__.Priva teClass object at 0x0117CDD0>}
### we are always one behind in the dict content

instance alpha called not so simple
=======
Note that instance beta was never recognized when it called "apparently
simple method".

I'm sure there must be a way to do this....

André

Jul 18 '05 #5
André wrote:
Using the method suggested by Steven Bethard, I *almost* got it working
the way I would like.
Here's my program:
===
.class PrivateClass(ob ject):
. dict = {}
. def not_so_simple_m ethod(self):
. for name in PrivateClass.di ct.keys():
. if PrivateClass.di ct[name] == self:
. print "instance " + name + " called not so simple"
. apparently_simp le_method = not_so_simple_m ethod

. def __init__(self):
. print "instance created"
. for name, value in globals().iteri tems():
. if isinstance(valu e, PrivateClass):
. PrivateClass.di ct[name] = value

.def public_class():
. return PrivateClass()

.print "=== start==="
.alpha = public_class()
.print "created alpha"
.print PrivateClass.di ct
.print "### alpha is not there\n"

.beta = public_class()
.print "created beta"
.print PrivateClass.di ct
.print "### we are always one behind in the dict content\n"

.alpha.apparent ly_simple_metho d()
.beta.apparentl y_simple_method ()


It looks like you want PrivateClass.di ct updated every time that
globals() is updated. You can just use globals directly instead:

py> class PrivateClass(ob ject):
.... def __init__(self, globals):
.... self.globals = globals
.... def apparently_simp le_method(self) :
.... for name, value in self.globals.it eritems():
.... if value is self:
.... print "instance %s called not so simple" % name
....
py> def public_class():
.... return PrivateClass(gl obals())
....
py> alpha = public_class()
py> alpha.apparentl y_simple_method ()
instance alpha called not so simple
py> beta = public_class()
py> beta.apparently _simple_method( )
instance beta called not so simple

On the other hand, the iteration in
PrivateClass.ap parently_simple _method has a very bad code smell...

Steve
Jul 18 '05 #6

Steven Bethard wrote:
André wrote:
Using the method suggested by Steven Bethard, I *almost* got it working the way I would like.
[snip]
It looks like you want PrivateClass.di ct updated every time that
globals() is updated.
yes, that is what I would like to do.
You can just use globals directly instead:

py> class PrivateClass(ob ject):
... def __init__(self, globals):
... self.globals = globals
... def apparently_simp le_method(self) :
... for name, value in self.globals.it eritems():
... if value is self:
... print "instance %s called not so simple" % name
...
py> def public_class():
... return PrivateClass(gl obals())
...
py> alpha = public_class()
py> alpha.apparentl y_simple_method ()
instance alpha called not so simple
py> beta = public_class()
py> beta.apparently _simple_method( )
instance beta called not so simple
That's exactly what I was looking for; thank you!
On the other hand, the iteration in
PrivateClass.ap parently_simple _method has a very bad code smell...

I'm not sure what you mean...
Is it because it makes use of information that is
exterior to the class, which is not passed as a parameter
to the method?
[feel free to ignore this question if you want; you have
already helped me tremendously!!!]

André

Jul 18 '05 #7
André Roberge wrote:
Behind the scene, I have something like:
robot_dict = { 'robot' = CreateRobot( ..., name = 'robot') }
and have mapped move() to correspond to
robot_dict['robot'].move()
(which does lots of stuff behind the scene.)

I have tested robot_dict[] with more than one robot (each with
its own unique name) and am now at the point where I would like
to have the ability to interpret something like:

alex = CreateRobot()
anna = CreateRobot()

alex.move()
anna.move()

etc. Since I want the user to learn Python's syntax, I don't
want to require him/her to write
alex = CreateRobot(nam e = 'alex')
to then be able to do
alex.move()


How do you get the commands from the user? Maybe you can preprocess the
user code?

py> class Robot(object):
.... def __init__(self, name):
.... self.name = name
.... def move(self):
.... print "robot %r moved" % self.name
....
py> user_code = """\
.... alex = Robot()
.... anna = Robot()
.... alex.move()
.... anna.move()"""
py> new_user_code = re.sub(r'(\w+)\ s+=\s+Robot\(\) ',
.... r'\1 = Robot(name="\1" )',
.... user_code)
py> print new_user_code
alex = Robot(name="ale x")
anna = Robot(name="ann a")
alex.move()
anna.move()
py> exec new_user_code
robot 'alex' moved
robot 'anna' moved

Steve
Jul 18 '05 #8
André wrote:
Steven Bethard wrote:
André wrote:
Using the method suggested by Steven Bethard, I *almost* got it
working
the way I would like.


[snip]
It looks like you want PrivateClass.di ct updated every time that
globals() is updated.

yes, that is what I would like to do.

You can just use globals directly instead:

py> class PrivateClass(ob ject):
... def __init__(self, globals):
... self.globals = globals
... def apparently_simp le_method(self) :
... for name, value in self.globals.it eritems():
... if value is self:
... print "instance %s called not so simple" % name
...
py> def public_class():
... return PrivateClass(gl obals())
...
py> alpha = public_class()
py> alpha.apparentl y_simple_method ()
instance alpha called not so simple
py> beta = public_class()
py> beta.apparently _simple_method( )
instance beta called not so simple


That's exactly what I was looking for; thank you!

On the other hand, the iteration in
PrivateClass. apparently_simp le_method has a very bad code smell...


I'm not sure what you mean...
Is it because it makes use of information that is
exterior to the class, which is not passed as a parameter
to the method?
[feel free to ignore this question if you want; you have
already helped me tremendously!!!]


There's a couple things I don't like about it:

(1) Generally, I don't like passing globals() around. It's probably
okay in this scenario though because if you want to have the user code
in a different module, you can do something like:
def public_class():
return PrivateClass(us ermodule.__dict __)

(2) The really bad code smell however is having to iterate through all
the values in globals to find the key you're looking for... Especially
when you have to check the type of each item... In a perfect world, you
would already have a PrivateClass->name mapping somewhere and this
should be a simple dict lookup instead of an iterative search... See my
other post about potentially pre-processing your user input to see how
you can convert the iteration to a simple attribute lookup.

Steve
Jul 18 '05 #9

Steven Bethard wrote:
André Roberge wrote:
Behind the scene, I have something like:
robot_dict = { 'robot' = CreateRobot( ..., name = 'robot') }
and have mapped move() to correspond to
robot_dict['robot'].move()
(which does lots of stuff behind the scene.)

I have tested robot_dict[] with more than one robot (each with
its own unique name) and am now at the point where I would like
to have the ability to interpret something like:

alex = CreateRobot()
anna = CreateRobot()

alex.move()
anna.move()

etc. Since I want the user to learn Python's syntax, I don't
want to require him/her to write
alex = CreateRobot(nam e = 'alex')
to then be able to do
alex.move()
How do you get the commands from the user? Maybe you can preprocess

the user code?

py> class Robot(object):
... def __init__(self, name):
... self.name = name
... def move(self):
... print "robot %r moved" % self.name
...
py> user_code = """\
... alex = Robot()
... anna = Robot()
... alex.move()
... anna.move()"""
py> new_user_code = re.sub(r'(\w+)\ s+=\s+Robot\(\) ',
... r'\1 = Robot(name="\1" )',
... user_code)
py> print new_user_code
alex = Robot(name="ale x")
anna = Robot(name="ann a")
alex.move()
anna.move()
py> exec new_user_code
robot 'alex' moved
robot 'anna' moved

Smack! (sound of hand slapping forehead).
Of course! This is *much* better.
(In all honesty, I have trouble reading regular expression
notation but I can decode it enough to understand that I can
do this - and I already asked a question today on the list
about regular expressions, so I have not excuse for not having
thought of an approach like this.)

I will be already 'processing' the code to make sure that
statements/words like: import, exec, eval, input, raw_input, vars,
chr, .... are not allowed in the user-defined instructions.
This will be just a simple addition.

Once again, thank you! Both for this, and for the other example which
taught me something about the use of locals(), globals(), and functions
that return classes. There are so many corners of Python to explore
:-)
Steve


Jul 18 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
22542
by: Martin | last post by:
I'd like to be able to get the name of an object instance from within a call to a method of that same object. Is this at all possible? The example below works by passing in the name of the object instance (in this case 'myDog'). Of course it would be better if I could somehow know from within write() that the name of the object instance was 'myDog' without having to pass it as a parameter. //////////////////////////////// function...
3
1860
by: Tim | last post by:
Hello Everyone I'd like to create a script/program that can locate all servers running DB2, finding out which instances are running/created and what databases are running under them but have been told but IBM support that this isn't currently possible for a client to do. I'd like to get a second opinion since the CCA seems to be able to manage it without any problems so the API must be there to do it. The main reason why I'd like...
275
12488
by: Astley Le Jasper | last post by:
Sorry for the numpty question ... How do you find the reference name of an object? So if i have this bob = modulename.objectname() how do i find that the name is 'bob'
0
9820
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10844
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10548
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10254
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9374
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7792
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6979
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5826
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4452
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.