HI !
I guess everything is in the question ... I was just wondering if there is a nice way in Python to shorten this pattern :
something = get_something()
if something:
do_a_thing_with(something)
Mean开发者_开发知识库ing that I would like to enter in the if
context only if the variable something
is not None (or False), and then in this context having this variable set automatically ! Is it possible with with
statement ?
PS : I don't want to have to DEFINE more stuff... I am looking for some statement to use on the fly ?!
This is as pythonic as it gets.
Things should be no more simplified than they are and no more complex than they should be.
See how the with statement works and providing a context guard. would be complicated enough.
- http://effbot.org/pyref/with.htm
- http://effbot.org/pyref/context-managers.htm
If it is a pattern that is very frequent in your code (as you suggested in a comment to @pyfunc's answer), you can just make it a function:
def safeProcessData(getData, handleData):
buffer = getData()
if buffer:
handleData(buffer)
In this case the parameters getData
and handleData
would be callables, meaning any function (free or member) and objects that implement __call__
.
As others have said, your existing code is already nice and short... If you really want a one-liner, try a list comprehension:
[do_a_thing_with(something) for something in [get_something()] if something]
精彩评论