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

前端 未结 10 736
名媛妹妹
名媛妹妹 2020-12-04 21:34

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

相关标签:
10条回答
  • 2020-12-04 22:16

    Simply try:

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

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


    Alternative solution would be to use a conditional expression in Python:

    <expression1> if <condition> else <expression2>
    

    but you'll end up repeating variable twice, for example:

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

    For variable assignments in loops, check in here.

    0 讨论(0)
  • 2020-12-04 22:21

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

    try:
       q = request.GET.get('q')
       print q
    except :
       pass
    
    0 讨论(0)
  • 2020-12-04 22:22

    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)
    
    0 讨论(0)
  • 2020-12-04 22:26

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

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

    this?

    0 讨论(0)
  • 2020-12-04 22:27
    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...

    0 讨论(0)
  • 2020-12-04 22:30
    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 讨论(0)
提交回复
热议问题