4

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
3
  • 1
    Well, Python still has ; so obj.attrib = 8; return obj should do that. But I guess, you are looking for a trick. I don't think there is one. Commented Apr 22, 2019 at 10:18
  • 2
    Python isn't the best language to code golf. There's no advantage to have this in one line instead of more readable two lines. Commented Apr 22, 2019 at 10:31
  • You don't even need to return anything, check my answer below! Commented Apr 22, 2019 at 13:31

2 Answers 2

6

You could do this:

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

This works because built-in function setattr returns None.

Sign up to request clarification or add additional context in comments.

4 Comments

Anyone reading this in the future will have to puzzle over what setattr may be returning here, since to anyone sensible this reads as "return whatever setattr returns or fall back to obj"…
I changed the answer a few minutes after posting it to include a reference to setattr function. And yes, this is a misuse of Python, a hack, and an exploit of a side-effect, but it is an answer to the given question.
I mean, if you use this in production code, anyone coming after you would be puzzling over this. So you'd need to include a comment line linking to this answer or the documentation to make the code really understandable, at which point you have two lines again… ;-)
I agree. And if the question was "Should I do this in a single line like this?" I would answer "No." :)
0

You don't need to return the object, the object you pass in the argument to the function will have the attrib set and you can refer it directly from the caller code.

class A:

    def __init__(self, attrib):
        self.attrib = attrib

def function(obj):
    obj.attrib = 8

obj = A(5)
#This line prints 5
print(obj.attrib)
#5
function(obj)
#This line prints 8
print(obj.attrib)
#8

Or a better approach might be:

class A:

    def __init__(self, attrib):
        self.attrib = attrib

    def function(self, attrib):
        self.attrib = attrib

obj = A(5)
print(obj.attrib)
#5
obj.function(8)
print(obj.attrib)
#8

2 Comments

While this represents best practice, it does not answer the question.
It obviates the need of return from function, invalidating the intent of the question!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.