Condition-Based Python Point-Syntax Functions

Is it possible in python to call a condition-based dot-syntax-function function. A simple example:

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

def lots_of_code():
  # lots of code

in

foo().(if condition: bar()).baz()
# lots of code only once
+4
source share
2 answers

No, It is Immpossible.

Attribute Reference Syntax

attributeref ::=  primary "." identifier

Quoting documentation ,

An attribute reference is the primary element, followed by a period and name.

the name must be a regular Python identifier , and identifiers cannot contain special characters such as (.

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

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

It is equivalent

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

primary.baz()

, , , .

+5

foo() , . f f.baz(). , , f foo().bar().

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

Source: https://habr.com/ru/post/1615396/


All Articles