How to make a reference to int by name in Python

I want to have a link that reads as "any variable of the name" x "points to" using ints, so that it behaves like:

>>> a = 1 >>> b = 2 >>> c = (a, b) >>> c (1, 2) >>> a = 3 >>> c (3, 2) 

I know I could do something similar with lists:

 >>> a = [1] >>> b = [2] >>> c = (a, b) >>> c ([1], [2]) >>> a[0] = 3 >>> c ([3], [2]) 

but this can easily be lost if you assign something instead of a or b instead of your elements.

Is there an easy way to do this?

+4
source share
6 answers

No, in Python there is no direct way to do this. The reason is that both scalar values ​​(numbers) and tuples are immutable. Once you establish a binding from a name to an immutable value (for example, the name c with a tuple (1, 2) ), you will do nothing but override c to change the value to which it is bound.

Note that in the second example, although the tuple itself is immutable, it contains references to mutable values. Thus, it seems that the tuple is changing, but the identity of the tuple remains constant, and only the mutable parts change.

+4
source

Whatever the possible solution that you came up with in the second last line, it will always destroy it:

 a = 3 

This will result in the assignment of completely new content to the variable. If a means an object property or something (or a key in a list, as in your own example), you cannot have a connection between the first and last a .

+2
source

If you just want the current values ​​to put in the tuple on the fly, you can use lambda. You will need to call c, not just return it or use it, but this may be acceptable in your situation. Something like that:

 >>> a = 1 >>> b = 2 >>> c = lambda: (a, b) >>> c() (1, 2) >>> a = 3 >>> c() (3, 2) 
+2
source

There is no way in Python, not only because numbers are immutable, but also because you don't have pointers. Wrapping a value in a list mimics what you have pointers, so you can do your best.

+1
source
 class ByRefValue(object): def __init__(self, value): self.value = value 

Go where you want, remember that you need to access the value element, not the entire object.


Alternatively, globals().get('a', 0) will return a if it is in the global namespace (or zero if it is missing).


Finally:

 import threading tls = threading.local() tls.a = 1 

If you import tls into each module where you need it, you will get the same value for a for each thread. Depending on how your program is configured, this may be acceptable, ideal or useless.

+1
source

You can try creating your own pointer class and your own pointer storage object to emulate the internal stack of the system.

0
source

All Articles