Reputation: 1085
Is this:
def outer(x):
def inner():
print x
return inner
>>> outer("foo")()
The same as this:
def outer(x):
def inner():
print x
return inner()
>>> outer("foo")
Both work, but is there a more pythonic way to write something like this?
Upvotes: 0
Views: 54
Reputation: 4757
They are different. In your example, the first will return a function, that you can use later, and the second will return None type, because you're returning nothing, just printing x.
Upvotes: 0
Reputation: 295443
Neither is "more pythonic" in absolute terms, because you would use them in different circumstances.
Returning a function to be called later is appropriate if you're generating a callback to be wired up somewhere else, closing over some inputs (with others to be filled in later), or for similar advanced use cases.
Returning a value or immediately performing a side-effecting action is appropriate if your callers will only be interested in that value or action, and you don't have any particular reason to split the operation into stages.
Upvotes: 3