אליהו פלג
אליהו פלג

Reputation: 13

How to use a string' value as an object name

I'm trying to do something like this:

user_id = 12345
"user_id" = user("...")  # "user" is my class
# I want to replace "user_id" with "12345"

Is it possible?

Upvotes: 1

Views: 593

Answers (1)

iBug
iBug

Reputation: 37227

If you really need this, you're better off with a dict:

my_objs = {}
user_id = 12345
my_objs[user_id] = User()
print(my_objs)

Then the output would be:

{12345: <__main__.User object at 0x123456789abc>}

You can always fetch the object with either of these:

another_id = 12345
my_objs[another_id]

my_objs[12345]

If you really, really need this but can't use a dict, getattr and setattr may help:

user_name = "hahaha"
setattr(__import__(__name__), user_name, User())

print(hahaha)

new_name = "hahaha"
assert hahaha is getattr(__import__(__name__), new_name)

which will generate the same output and the assertion will pass.

Note this method isn't going to work all well inside a function, it's only good at module level.

Upvotes: 3

Related Questions