ForeverLearning ForeverLearning - 3 months ago 25
Python Question

Python - Pass a variable to lambda if it exists

I'm curious about how to make code more efficient in Python, I've got to execute an action, which may or may not have a payload attached depending on the length of a list.

Right now, I'm using an if statement to determine if there is a payload. Is there a better or cleaner way to find this?

#If payload, execute action with it
if(len(data) > 1):
action= mec.action(data[1])
#If no payload, then just execute action
else:
action= mec.action()
return action

Answer

The code is efficient as is - instead of optimising for efficiency, try optimising for clarity first. If the code then becomes a performance hotspot... think about looking at the efficiency.


Remembering that a return ends a function; this is a slightly cleaner alternative:

# execute with payload if exists
if(len(data) > 1):
    return mec.action(data[1])
# execute without payload 
# this isn't reached if len(data) > 1
return mec.action()