简体   繁体   中英

python statement with `or` inside square brackets

This is a code snippet I pasted from a setup.py python file. I am new to python and don't understand this build_args variable. Could someone give me some explanation for that?

build_args = [NINJA or MAKE]

# control the number of concurrent jobs
if self.jobs is not None:
    build_args.extend(['-j', str(self.jobs)])

subprocess.check_call(build_args)

build_args' instantiation is simply evaluating a logical boolean OR statement inside of the list a list structure. After the OR statement has been evaluated there will simply be a single boolean value stored in build_args. (props to ukemi, beat me to the punch)

Since it was also included in the code snippet I'd add that info for '.extend()' following can be found here . Essentially .extend() then just appends all items of an iterable structure on the end of the list, so build_args' content would then be [<boolean>, '-j', <job_string>]

Use:

build_args = [NINJA or MAKE]
  • If NINJA is "truthy", then build_args = [NINJA]
  • If NINJA is "falsy", then build_args = [MAKE]


Note: Python's Truthy and Falsy - generalized Booleans

In python there are other values equivalent to True and False , other than the booleans themselves:

In the context of Boolean operations, and also when expressions are used by control flow statements, the following values are interpreted as false:

  • False
  • None
  • numeric zero of all types
  • empty strings and containers (including strings, tuples, lists, dictionaries, sets and frozensets)

All other values are interpreted as true.


Truth table for or :

x y x or y
True True x
True False x
False True y
False False y

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