tags:

views:

83

answers:

3

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)

Meaning 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 ?!

+5  A: 

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.

pyfunc
Which means that I could use it for this, but I would have to create a ugly hacky context manager... right ? Hmmm ... I was just wondering if there is something standard, because it is a pattern that is very very frequent in my code !
sebpiq
@sebpiq : This is clear and more readable enough. :)
pyfunc
Yeah ok ... So no readability sacrifices for saving one line of code today :)
sebpiq
+1  A: 

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__.

Space_C0wb0y
Yeah that's a good way to do it, but I was just wondering if there is a standard way... like a statement I am not aware of, or something. But looks there ain't !
sebpiq
+1  A: 

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]
Frédéric Hamidi
Wow ! That's a good one ! But actually I don't really want to sacrifice readability.
sebpiq
If do_a_thing_with() returns a value you should add `[0]` to the end to get a single value not a list. I'm ashamed to admit I thought of this hideous way of doing it as well!
neil