i hope that after 4 years my late answer will be useful
Python has setattr
function to set attribute of given object. You can use it in your lambda expression.
setattr
is useful when you want to programmatically-correctly (sorry) set some class or class' instance. It is not used frequently because it is easier to assign variables directly with =
expression. But for lambdas... It is a salvation.
Also, iterables that support settign item (such as list), you can use <iter>.__setitem__
.
Option 1. If you know the name of variable you're assigning.
x = lambda nameofvar, value: setattr(__builtins__, nameofvar, value)
# abc does not exist right now. Assigning and setting it to 10
x('abc', 10)
print(abc) # output: 10
alt, if you want to set object's attribute:
class MyClass:
my_attr = False
def __init__(self, value):
self.value = value
myinstance = MyClass(25)
x = lambda obj, nameofvar, value: setattr(obj, nameofvar, value)
short_x = lambda nameofvar, value: setattr(MyClass, nameofvar, value)
# ^^^ this one works only for MyClass' attributes.
print(MyClass.my_attr) # output: False
x(MyClass, 'my_attr', True) # Changing MyClass' my_attr's value
print(MyClass.my_attr) # output: True
x(MyClass, 'my_attr2', 5) # Assigning new attribute to MyClass
print(MyClass.my_attr2) # output: 5
short_x('my_attr2', 123) # Setting MyClass' my_attr2 to 123
print(MyClass.my_attr2) # output: 123
print(myinstance.value) # output: 25
x(myinstance, 'value', 500)
print(myinstance.value) # output: 500
Option 2. Make a custom class and turn variable into its instance.
class Value:
def __init__(self, value):
self.value = value
x = lambda var, newvalue: setattr(var, 'value', newvalue)
a = Value(15)
print(a.value) # output: 15
x(a, 25)
print(a.value) # output: 25
Option 3. To set object's item.
lst = [15, 30, 45, 60, 75, 90]
x = lambda iterable, item, value: iterable.__setitem__(item, value)
print(lst) # output: [15, 30, 45, 60, 75, 90]
x(lst, 2, 1000)
print(lst) # output: [15, 30, 1000, 60, 75, 90]