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 =
?
In R programming, assign() method is used to assign the value to a variable in an environment.
In Python, we can assign a function to a variable. And using that variable we can call the function as many as times we want. Thereby, increasing code reusability. Simply assign a function to the desired variable but without () i.e. just with the name of the function.
paste is % operator in python. using apply you can make new value and assign it to new column.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With