简体   繁体   中英

Python dot-syntax-functions based on condition

Is it possible in python to call dot-syntax-function based on condition. Simple example to turn:

if condition:
  foo().bar().baz()
  lots_of_code()
else:
  foo().baz()
  lots_of_code()

def lots_of_code():
  # lots of code

into:

foo().(if condition: bar()).baz()
# lots of code only once

No, it is not possible.

The syntax for attribute reference is

attributeref ::=  primary "." identifier

Quoting the documentation ,

An attribute reference is a primary followed by a period and a name

name must be a regular Python identifier and identifiers can't contain special characters like ( .

However, you can use a simple conditional expression to select primary :

(foo().bar() if condition else foo()).baz()

It's equivalent to

if condition:
    primary = foo().bar()
else:
    primary = foo()

primary.baz()

Note that in this case we have to use parentheses, because attribute reference has higher precedence than conditional expression.

Since foo() is called in either case, start by doing so unconditionally. Save that object to f , with the intention of calling f.baz() . Before that, though, check your condition to see if f should really be the result of foo().bar() .

f = foo()
if condition:
    f = f.bar()
f.baz()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM