Marcus
Marcus

Reputation: 11

Getting the identifier name of an instance in python

I haven't found anything. I want to do this without passing the name inside the constructor.

class foo:
   pass
something = foo()

I want each instance of foo to be aware of its initial identifier name. In this case the instance of foo() I created should be aware that its identifier is the string "something"

I am working on a small api and this would be a very elegant approach, unfortunately I haven't seen anything like this done.

Thanks,

Upvotes: 1

Views: 259

Answers (3)

Paulo Scardine
Paulo Scardine

Reputation: 77251

As far as I know, in Python a variable is just a name referring to some object instance. You can have many names pointing to the same instance; the instance is not aware of its names (nor should be, IMHO); the same name can be reused later to point to other instance from a complete different class.

Given the Python data model is hard to see why would be useful for the object to know how it is named in some namespace.

You can store references to your instances in a class variable or another container, but it is not very common in Python - because namespaces are such natural and elegant containers.

Upvotes: 2

9000
9000

Reputation: 40884

You can't. Creation of an object is totally independent from assigning a reference to that object to some named variable.

foo().doSomething() — an instance of foo is not bound to any name and probably gets garbage collected right after the call.

a[1].moo = foo() — what's the name, again?

a = foo()
b = a # is name of foo 'a' or 'b'? both point to the same instance
a = None # but 'a' is gone, so now the name is 'b'?..

OTOH, passing a name to the constructor is painless:

my_foos = {}
for name in ('a', 'b', 'c'):
  my_foos[name] = foo(name)

You may even rudely assign an instance attribute, if you won't change the constructor for some reason:

my_foos = {}
for name in ('a', 'b', 'c'):
  a_foo = foo()
  a_foo.my_mame = name # here
  my_foos[name] = a_foo

And if you're into the dark side, you finally can add your foos to global namespace: globals().update(my_foos) — now you have global names a, b and c, each referring to an aptly-named foo.

And, for foo's sake, name your classes with a capital initial letter :)

Upvotes: 4

John Kugelman
John Kugelman

Reputation: 361585

Even if you could do this—which you can't—it would be an abuse of the language. For the sanity of whoever reads your code, please avoid hidden "magic" behavior. Python programmers would not expect their local variable names to be meaningful and actually be exposed to outside code.

Upvotes: 4

Related Questions