6

In R, I can use assign to assign a value to a name in environment on the fly (rather than <-.

Example:

> assign('x', 1)
> x
[1] 1

Does Python has an equivalent to assign rather than =?

mallet
  • 2,454
  • 3
  • 37
  • 64

2 Answers2

11

The Python equivalent to R's assign() is assignment to globals():

globals()['x'] = 1

But you should not do this, because it is a sign of poor code in 99% of cases. If you want to store values by name, use a dict:

stuff = {}
stuff['x'] = 1
John Zwinck
  • 239,568
  • 38
  • 324
  • 436
  • 3
    @intentionallyleftblank: Sure, but then the name is not a variable. You don't need `assign()` in R to assign a value to a name which is directly specified in the code. – John Zwinck Aug 08 '18 at 12:58
2

What is also possible to do, but for security reasons less recommended, is the use of eval and exec:

exec('x = 1')
eval('x')
eval('x + 5')
exec('y = x + 5')
eval('y')

Instead if you have classes and/or class instances, I recommend using setattr and getattr:

class A():
    pass
a = A()
setattr(a, 'x', 999)
a.x  # returns 999
getattr(a, 'x')  # same as a.x
A.x  # raises AttributeError: type object 'A' has no attribute 'x', since x is instance variable
setattr(A, 'x', 99)  # assign class variable
A.x  # returns 99
a.x  # still returns 999! --> instance variable

What is a quite important point here: Setting the class variable will not overwrite the instance variable.

JE_Muc
  • 5,403
  • 2
  • 26
  • 41