Reputation: 47071
I tried to write a function which can return a reference of an element for assginment, the sample code looks like this (Python3) :
row_a = ["rowname","items1","items2"]
def rowname(row):
return row[0]
rowname(row_a) = "another_rowname"
However, it will not work because the intepreter complains like:
SyntaxError: can't assign to function call
Does anyone have idea about how to implement a function like this?
Upvotes: 1
Views: 822
Reputation: 47071
Just found a ugly way .. Thougn setattr
needed..
row_a = ["rowname","items"]
def rowname(row):
class inner:
def __init__(self):
self.__dict__["to_l"] = None
def __setattr__(self,name,value):
row[0] = value
return inner()
rowname(row_a).to_l = 20
print(row_a)
Upvotes: 0
Reputation: 33
Return value from a function can't be used as a variable. You can rather assign the return value to a variable. Your list definition sees like you wanted to create a dictionary. Why not sat exactly what you expected to get?
Upvotes: 0
Reputation: 359966
There isn't a Pythonic way of doing this. You cannot return an lvalue in Python – Python isn't C++! If you just want use a function to to set the value of the first element of a list, just do that:
row_a = ["rowname","items1","items2"]
def set_rowname(row, value):
row[1] = value
set_rowname(row_a, "another_rowname")
Upvotes: 1