How to get an object's name as a string?

S

Shannon Mayne

I would like to create objects with algorithmically determined names
based on other object names and use object names for general algorithm
input.

How would one extract the name of an object from an object instance as
a string. I would think that it is stored as an attribute of the
object but successive 'dir()' calles haven't found me the attribute
with the namestring.

My thanks!
 
L

Larry Bates

Shannon said:
I would like to create objects with algorithmically determined names
based on other object names and use object names for general algorithm
input.

How would one extract the name of an object from an object instance as
a string. I would think that it is stored as an attribute of the
object but successive 'dir()' calles haven't found me the attribute
with the namestring.

My thanks!

Once again (there have been many posts on this subject). Objects can have more
than one name in Python. Therefore there is not a one-to-one correspondence
between an object instance and name(s) that point to it.

Example:

a = myObject()
b = a
c = a

now a, b, c all point to the same object. How would you define it's "name".

You are certainly free to store a name as an attribute to the object, but the
linkage would then be purely logical.

Example:

objects = []
objects.append(myObject('a'))
#
# Find object with name == 'a'
#
obj = None
for object in objects:
if object.name == 'a':
obj = object


-Larry
 
J

Joe Strout

I would like to create objects with algorithmically determined names
based on other object names and use object names for general algorithm
input.

What do you mean by the "name" of an object? Objects don't generally
have names, unless you explicitly define a .name property and assign
them names.

(Variables have names, of course, but a variable isn't an object --
it's just a reference to an object. Many variables may refer to the
same object, so it doesn't make any sense to ask for the name of THE
variable which may be referring to an object at the moment.)
How would one extract the name of an object from an object instance as
a string. I would think that it is stored as an attribute of the
object but successive 'dir()' calles haven't found me the attribute
with the namestring.

As noted above, there is no built-in name attribute. Define one,
perhaps like this:

class Foo():
def __init__(name):
self.name = name

Now your Foo objects have a name attribute, and if "x" is a reference
to such an object, you would access that as "x.name".

It's still unclear what you intend to do with these, but if at some
point you want to access objects by their names (from user input or
whatever), then you'll also need a dictionary to map names to
objects. So to your __init__ function, you might add something like
this:

name_map[name] = self

where name_map was initialized to {} at the top of the file. Then you
can use name_map to look up any object of this class by name.
Remember that this will keep these objects from automatically
disappearing when there are no other references (other than the map)
to them. If that's a problem, explicitly remove them from the map
when you know you're done with them, or use weak references.

Best,
- Joe
 
S

Steven D'Aprano

What do you mean by the "name" of an object? Objects don't generally
have names, unless you explicitly define a .name property and assign
them names.

(Variables have names, of course, but a variable isn't an object -- it's
just a reference to an object. Many variables may refer to the same
object, so it doesn't make any sense to ask for the name of THE variable
which may be referring to an object at the moment.)

That explanation makes no sense. Given the assignment:

x = 57

if the name of x isn't 'x', then what on earth can it possibly mean to
ask for the name of a variable?

In languages like Python, the term "variable" is misleading and
confusing. Python's programming model has objects (values), and names.
Best to use language that describes what Python actually does, rather
than use language that describes what other languages do.
 
S

Steve Holden

Steven said:
That explanation makes no sense. Given the assignment:

x = 57

if the name of x isn't 'x', then what on earth can it possibly mean to
ask for the name of a variable?
He didn't ask for the name of a variable, he asked for the name of an
object. You may choose to equate them, but they aren't the same thing.
In languages like Python, the term "variable" is misleading and
confusing. Python's programming model has objects (values), and names.
Best to use language that describes what Python actually does, rather
than use language that describes what other languages do.
Objects in Python *don't* have names. Period. In Python we don't
normally talk about variables anyway, except when speaking loosely, we
talk about binding names. But please don't let this start another round
of "Python programmers don't know how to describe the language". You
have already made your opinions on that score more than clear.

l = []
l.append(l)
del l

What's the name of the list formerly known as "l"?

regards
Steve
 
S

Steve Holden

Steven said:
That explanation makes no sense. Given the assignment:

x = 57

if the name of x isn't 'x', then what on earth can it possibly mean to
ask for the name of a variable?
He didn't ask for the name of a variable, he asked for the name of an
object. You may choose to equate them, but they aren't the same thing.
In languages like Python, the term "variable" is misleading and
confusing. Python's programming model has objects (values), and names.
Best to use language that describes what Python actually does, rather
than use language that describes what other languages do.
Objects in Python *don't* have names. Period. In Python we don't
normally talk about variables anyway, except when speaking loosely, we
talk about binding names. But please don't let this start another round
of "Python programmers don't know how to describe the language". You
have already made your opinions on that score more than clear.

l = []
l.append(l)
del l

What's the name of the list formerly known as "l"?

regards
Steve
 
J

Joe Strout

That explanation makes no sense. Given the assignment:

x = 57

if the name of x isn't 'x', then what on earth can it possibly mean to
ask for the name of a variable?

Perhaps you're skimming rather than reading carefully? Variables do
have names, as I pointed out, and the name of x is indeed 'x'. But
that's not what the OP was asking for -- in your example, he'd be
asking for the name of 57 (expecting it to be 'x'). Numbers don't
have names; objects don't have names; variables have names, and may
refer to numbers or objects.
In languages like Python, the term "variable" is misleading and
confusing.

Oh good grief. Now you're going to try to discard the standard term
"variable" as well?

All right then, if you really insist on making Python more mysterious
by making up new terms for perfectly ordinary and standard programming
concepts, then I suggest the following:

variable: "ariablevay"
value: "aluvay"
reference: "eferencevay"
call-by-value: "allcay-ibay-aluvay"
call-by-reference: (no term needed, since Python doesn't have it)

There. Now we've got a simple mapping from standard terminology to
properly mystical Python-culture terms that are nonetheless easy to
learn. Agreed?

Best,
- Joe

P.S. Shannon: don't listen to Steven. He's out to confuse you and
make Python seem much harder and complex than it really is.
 
J

Joe Strout

Objects in Python *don't* have names. Period. In Python we don't
normally talk about variables anyway, except when speaking loosely, we
talk about binding names. But please don't let this start another
round
of "Python programmers don't know how to describe the language". You
have already made your opinions on that score more than clear.

As have I, I suppose, and I'll try to quit engaging in that argument
in the future.
l = []
l.append(l)
del l

What's the name of the list formerly known as "l"?

Hey, that's a very nice little demonstration of an orphaned object.
Thanks for sharing it!

Best,
- Joe
 
A

alex23

I would like to create objects with algorithmically determined names
based on other object names and use object names for general algorithm
input.

The simplest and best option here is to store the objects in a
dictionary with their keys being the generated names.
 
S

ShanMayne

The simplest and best option here is to store the objects in a
dictionary with their keys being the generated names.

Thanks. Indeed Alex, that may well be the simplest way, to have an
overarching Dictionary of references/names and objects.

However this does not help me to use the reference/name of an object I
imported instead of created.

#-----#

There has been much debate over terminology but I was under the
impression that there was a simple input-output defined task in
question.

Inherently a the variable/name/reference maps to the object it was
assigned to. The question is can one map it the other way? If there
are multiple assignments to the same object can they be listed? This
applies to the "names" object atributes as well.

Joe has mentioned that I shouldn't need to do this and should perhaps
rethink my problem formulation. Nonetheless, I would still like to
know how it might be done.

Thanks
Shannon
 
A

alex23

However this does not help me to use the reference/name of an object I
imported instead of created.

I've never really understood these requests (and they come up a lot).
Unless you're doing a '*' import, you'll already know the bound names
of the objects you're importing. If you -are- doing a '*' import and
you -don't- know what objects are being imported, how will you refer
to the object to find out its name?

However, maybe one of the following examples will be of use.

Assume a module 'items' that contains:

a = 1
b = 'string'

The best way would be to use the module as it is intended, as a
namespace:
>>> import items
>>> names = [x for x in dir(items) if not '__' in x] # ignore special objects
>>> names ['a', 'b']
>>> one = getattr(items, names[0])
>>> two = getattr(items, names[1])
>>> one 1
>>> two
'string'

Another way is to look through the variables in the current scope:
>>> before = set(locals())
>>> before.add('before') # you want to ignore this object too
>>> from items import *
>>> names = list(set(locals()).difference(before))
>>> names ['a', 'b']
>>> one = locals()[names[0]]
>>> two = locals()[names[1]]
>>> one 1
>>> two
'string'

Do either of these help with your problem?
 
S

ShanMayne

Indeed they do. My delighted thanks. You have most precisely addressed
the problem I intended to convey.

I should have given the case of module attributes a moments further
thought, an obvious answer. The locals() was unknown to me (rookie
gaps).

Thank you for the elaborated illustration.

good stuff.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,599
Members
45,175
Latest member
Vinay Kumar_ Nevatia
Top