Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python equivalent of R assign

Tags:

python

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 =?

like image 547
mallet Avatar asked Aug 08 '18 12:08

mallet


People also ask

What does assign () do in R?

In R programming, assign() method is used to assign the value to a variable in an environment.

Can you assign function to variable in Python?

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.

What is paste in Python?

paste is % operator in python. using apply you can make new value and assign it to new column.


2 Answers

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
like image 121
John Zwinck Avatar answered Sep 28 '22 07:09

John Zwinck


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.

like image 31
JE_Muc Avatar answered Sep 28 '22 06:09

JE_Muc