2

Before you say to use a dictionary, I want to change the value of the actual variable.

This is what happens with the standard dict strategy: (Note that I'm not necessarily using a list, the value could be a complex class type or just a regular int)

>>> dict = {}
>>> x = [1,2,3]
>>> dict["x"] = x
>>> x
[1, 2, 3]
>>> dict["x"]
[1, 2, 3]
>>> dict["x"] = [4,5,6]
>>> dict["x"]
[4, 5, 6]
>>> x
[1, 2, 3]
>>>

Anyone know a way to do this so that the actual contents of x are changed as well? copy.deepcopy doesn't do the trick either. (as in 'dict["x"] = copy.deepcopy(x)')

10
  • 2
    You have not convinced me that you don't need a dictionary. Commented Mar 27, 2014 at 20:20
  • Why do you want to access variables by their names? See Keep data out of variable names Commented Mar 27, 2014 at 20:21
  • @LevLevitsky I would like x to contain [4,5,6] after my assignment. Commented Mar 27, 2014 at 20:21
  • But why do you want to access a variable x using a string? Why not just continue to access it as dict["x"]? Commented Mar 27, 2014 at 20:23
  • 1
    I don't own the code, can't refactor it. Commented Mar 27, 2014 at 20:27

2 Answers 2

4

Use slice assignment:

>>> d = {}
>>> x = [1, 2, 3]
>>> d['x'] = x
>>> d['x'][:] = [4, 5, 6]
>>> x
[4, 5, 6]
>>> d['x']
[4, 5, 6]

For other data types make sure you modify them in-place instead of assigning them to new variables. Note that for immutable data types like int, strings etc there are no in-place operations available.

Sign up to request clarification or add additional context in comments.

9 Comments

This won't work for the OP: (Note that I'm not necessarily using a list, the value could be a complex class type or just a regular int).
Sure, but the principle is the same -- modify the data in-place, don't overwrite it.
@ThaneBrimhall: there's no way to modify an int in place.
Actually, it complains if I'm using longs, for example. (" 'long' object does not support item assignment")
@ThaneBrimhall: But the value of an int can be changed, (x = 1, or exec("%s = 1" % varname) I suppose) which is presumably what the OP wants (even though it's a bad idea).
|
2

this is a horrible idea and stinks of horrible code smell ... dont do this you need to refactor the code to be sensible .... this is a terrible idea but if you want

mutables = {
"x":x,"y":y,"Z":Z #make sure the dict key is exactly the same as var name
}

mutables['x'] = [5,6,7]
for k,v in mutables.items():
    globals()[k] = v

note that you will need to be in the same global scope as the original variables

1 Comment

Yeah I know it's a bad situation, I wish the owners of the code would refactor it because I don't have permission to change it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.