Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change attribute for object and return the object in one line

Tags:

python

Is is possible to rewrite this code:

def function(obj):
    obj.attrib = 8
    return obj

So the set of the attribute and the return line appears in only one line? Something like:

def function(obj):
    return obj.attrib = 8 # of course, this does not work
like image 692
Rodrigo Serna Pérez Avatar asked Oct 28 '25 15:10

Rodrigo Serna Pérez


1 Answers

You could do this:

def function(obj):
    return setattr(obj, 'attrib', 8) or obj

This works because built-in function setattr returns None.

like image 174
gonadarian Avatar answered Oct 30 '25 09:10

gonadarian