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

前端 未结 10 740
名媛妹妹
名媛妹妹 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:39

    PEP 572 introduces Assignment Expressions. From Python 3.8 and onwards you can write:

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

    Here are some more examples from the Syntax and semantics part of the PEP:

    # Handle a matched regex
    if (match := pattern.search(data)) is not None:
        # Do something with match
    
    # A loop that can't be trivially rewritten using 2-arg iter()
    while chunk := file.read(8192):
       process(chunk)
    
    # Reuse a value that's expensive to compute
    [y := f(x), y**2, y**3]
    
    # Share a subexpression between a comprehension filter clause and its output
    filtered_data = [y for x in data if (y := f(x)) is not None]
    

提交回复
热议问题