shinji
shinji

Reputation: 53

Python class definition based on a condition

I found a similar class definition as below in a Python code base. It seems there is no similar examples in the official documents. Very hard to find similar thing by Google and searching in the forum. May anyone help me to understand the principle in Python behind this?

class a: pass
class b: pass
condition = True
class c(a if condition == True else b): pass

Upvotes: 5

Views: 1092

Answers (1)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250941

a if condition == True else b is a ternary expression.

It means use a as base class if condition equals True else use b.

As condition == True is True so it uses a:

>>> class c(a if condition == True else b): pass
>>> c.__bases__
(<class __main__.a at 0xb615444c>,)

Examples:

>>> print 'foo' if 0>1 else 'bar'
bar
>>> print 'foo' if 1>0 else 'bar'
foo

From the docs:

The expression x if C else y first evaluates the condition, C (not x); if C is true, x is evaluated and its value is returned; otherwise, y is evaluated and its value is returned.

Upvotes: 5

Related Questions