tags:

views:

853

answers:

7

Hello,

Sorry if this is Python 101 but I don't even know what to search for to get the answer. I come from a PHP background and would like to know if there's a way to do this in Python.

In PHP you can kill 2 birds with one stone like this:

Instead of:

if(getData()){
    $data = getData();
    echo $data;
}

I can do this:

if($data = getData()){
    echo $data;
}

You check to see if getData() exists AND if it does, you assign it to a variable in one statement.

I wanted to know if there's a way to do this in Python? So instead of doing this:

if request.GET.get('q'):
    q = request.GET.get('q')
    print q

avoid writing request.GET.get('q') twice.

Thanks, g

+9  A: 

Probably not exactly what you were thinking, but...

q = request.GET.get('q')
if q:
    print q

this?

Amber
yeah, that's right. the pattern is to use a variable if and only if it exists (meaning it gives a valid value, i.e. anything but *False*).
omouse
Thanks, looks like this is the best way to do it. As @Adam says, it's not possible to do this in Python. Thanks.
givp
The limitation of this solution is if you want to use it in a series of if-elif-elif-elif etc. For example, see this other SO question: http://stackoverflow.com/questions/122277/how-do-you-translate-this-regular-expression-idiom-from-perl-into-python
Craig McQueen
+5  A: 

See my 8-year-old recipe here for just this task.

Alex Martelli
You have a pretty smart 8-year-old! ;)
unutbu
@unutbu, heh - that would be my (older) cat as my kids are a bit older... my younger daughter's just started her PhD in telecom engineering (advanced radio systems, mostly)...;-)
Alex Martelli
A: 

Well, this would be one way

q = request.GET.get('q')
if q:
    print q

A briefer (but not superior, due to the call to print of nothing) way would be

print request.GET.get('q') or '',
Grumdrig
+2  A: 
q = request.GET.get('q')
if q:
    print q
else:
    # q is None
    ...

There's no way of doing assignment and conditionals in one go...

Adam
Explicit is better than implicit. Readability counts. Special cases aren't special enough to break the rules. You are saving so much vertical space in your code by not writing all those lines with nothing but a right brace, so why not go for clarity in Python? Personally, I cut my teeth on C and have been writing Python code for 12 years now, and I never realised this feature was missing. You just don't need to do this.
Michael Dillon
@Michael: I agree in almost all cases. I am just missing it in the specific use case of testing multiple regular expressions, as described in this other SO question: http://stackoverflow.com/questions/122277/how-do-you-translate-this-regular-expression-idiom-from-perl-into-python
Craig McQueen
A: 

If get() throws an exception when it's not there, you could do

try:
   q = request.GET.get('q')
   print q
except :
   pass
Rizwan Kassim
A: 

A variation on Alex's answer:

class DataHolder:
    def __init__(self, value=None, attr_name='value'):
        self._attr_name = attr_name
        self.set(value)
    def __call__(self, value):
        return self.set(value)
    def set(self, value):
        setattr(self, self._attr_name, value)
        return value
    def get(self):
        return getattr(self, self._attr_name)
save_data = DataHolder()

Usage:

if save_data(get_input()):
    print save_data.value

or if you prefer an alternative interface:

if save_data.set(get_input()):
    print save_data.get()

I would find this helpful to test a series of regular expressions in an if-elif-elif-elif etc construct, as in this SO question:

import re

input = u'test bar 123'
save_match = DataHolder(attr_name='match')
if save_match(re.search('foo (\d+)', input)):
    print "Foo"
    print save_match.match.group(1)
elif save_match(re.search('bar (\d+)', input)):
    print "Bar"
    print save_match.match.group(1)
elif save_match(re.search('baz (\d+)', input)):
    print "Baz"
    print save_match.match.group(1)
Craig McQueen
A: 
config_hash = {}
tmp_dir = ([config_hash[x]  for x in ["tmp_dir"] if config_hash.has_key(x)] or ["tmp"])[0]
print tmp_dir
config_hash["tmp_dir"] = "cat"
tmp_dir = ([config_hash[x]  for x in ["tmp_dir"] if config_hash.has_key(x)] or ["tmp"])[0]
print tmp_dir
louis_xv