How to avoid writing request.GET.get () twice to print it?

I come from the background of PHP and would like to know if there is a way to do this in Python.

In PHP, you can kill two birds with one stone:

Instead:

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

I can do it:

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

You check if getData() exists, and if so, you assign it to a variable in one statement.

I wanted to know if there is a way to do this in Python? So instead:

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

do not write request.GET.get('q') twice.

+38
python dictionary if-statement
Nov 02 '09 at 21:59
source share
9 answers

Probably not quite what you were thinking about, but ...

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

+25
Nov 02 '09 at 22:02
source share

See my 8 year old recipe here for this purpose only.

 # In Python, you can't code "if x=foo():" -- assignment is a statement, thus # you can't fit it into an expression, as needed for conditions of if and # while statements, &c. No problem, if you just structure your code around # this. But sometimes you're transliterating C, or Perl, or ..., and you'd # like your transliteration to be structurally close to the original. # # No problem, again! One tiny, simple utility class makes it easy...: class DataHolder: def __init__(self, value=None): self.value = value def set(self, value): self.value = value; return value def get(self): return self.value # optional but handy, if you use this a lot, either or both of: setattr(__builtins__,'DataHolder',DataHolder) setattr(__builtins__,'data',DataHolder()) # and now, assign-and-set to your heart content: rather than Pythonic while 1: line = file.readline() if not line: break process(line) # or better in modern Python, but quite far from C-like idioms: for line in file.xreadlines(): process(line) # you CAN have your C-like code-structure intact in transliteration: while data.set(file.readline()): process(data.get()) 
+24
Nov 02 '09 at 22:03
source share

Alex answer option:

 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() 

Using:

 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() 

It would be useful for me to check a number of regular expressions in the if-elif-elif-elif construct, etc., 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) 
+9
Nov 27 '09 at 1:03
source share
 q = request.GET.get('q') if q: print q else: # q is None ... 

Cannot complete assignment and conditional conditions at a time ...

+2
Nov 02 '09 at 22:04
source share

If get () throws an exception, if it does not exist, you can do

 try: q = request.GET.get('q') print q except : pass 
+2
Nov 02 '09 at 22:13
source share

Well, that will be one way

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

Bryfer (but not higher, due to a print call nothing) will be

 print request.GET.get('q') or '', 
0
Nov 02 '09 at 22:04
source share
 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 
0
Jun 29 2018-10-06T00:
source share

A possible way to do this, without having to set the variable earlier, could be as follows:

 if (lambda x: globals().update({'q':x}) or True if x else False)(request.GET.get('q')): print q 

.. this is just for fun - this method should not be used because it is an ugly hack that is hard to understand at a glance and it creates / overwrites a global variable (only if the condition is met)

0
Aug 21 '12 at 17:50
source share

Just try:

 print(request.GET.get('q', '')) 

which basically prints nothing if the first argument is missing (see dict.get ).




An alternative solution would be to use a conditional expression in Python:

 <expression1> if <condition> else <expression2> 

but you end up repeating the variable twice, for example:

 print(request.GET.get('q') if request.GET.get('q') else '') 



For variable assignments in loops, check here .

0
May 23 '15 at 7:10
source share



All Articles