5

ab.py

from ddr import Options
debugElmo     = int(Options.env['GG_DEBUG_ELMO'])
postdevElmo   = int(Options.env['GG_POST_DEV_ELMO'])

选项.py

vars_of_interest = (
    'AA_PYTHON',
    'GG_POST_DEV_ELMO',
    'GG_DEBUG_ELMO',
    )
env = dict((var, os.getenv(var, 0)) for var in vars_of_interest)

我不确定发生了什么,env = dict((var, os.getenv(var, 0)) for var in vars_of_interest)因为我对 python 还很陌生

env是Options.py中python中的一个函数吗?
什么是字典()?
var 是来自的变量int(Options.env['GG_DEBUG_ELMO'])吗?

4

2 回答 2

7

You can often learn what Python code is doing by looking at its pieces in the Python interpreter:

>>> vars_of_interest
('AA_PYTHON', 'GG_POST_DEV_ELMO', 'GG_DEBUG_ELMO')

>>> import os

>>> [(var, os.getenv(var, 0)) for var in vars_of_interest]
[('AA_PYTHON', 0), ('GG_POST_DEV_ELMO', 0), ('GG_DEBUG_ELMO', 0)]

>>> env = dict((var, os.getenv(var, 0)) for var in vars_of_interest)
>>> env
{'AA_PYTHON': 0, 'GG_DEBUG_ELMO': 0, 'GG_POST_DEV_ELMO': 0}

env = dict(...) makes env a dict. If you are ever unsure what an object is, you can always ask it what its type is:

>>> type(env)
dict

A dict is a mapping between keys and values. In this case, env is a mapping between strings such as 'AA_PYTHON' and values, such as 0.

var is a temporary variable used in the generator expression

((var, os.getenv(var, 0)) for var in vars_of_interest)

The for var in vars_of_interest in the generator expression tells Python to iterate over the items in the tuple vars_of_interest, and assign the values to var one-by-one as it iterates through the loop. The generator expression is an iterator. The iterator yields the values of (var, os.getenv(var, 0)) for each var.

The expression (var, os.getenv(var, 0)) is a tuple which can be thought of as a key-value pair. var is the key, os.getenv(var, 0) is the value. os.getenv looks up the environment variable var (e.g. 'AA_PYTHON') and returns the value of the environment variable if it exists, otherwise, it returns 0.

When dict is passed an iterator of key-value pairs, as is being done in the expression

dict((var, os.getenv(var, 0)) for var in vars_of_interest)

it returns a dict which maps the given keys to the given values.

See here for more information on Python dicts.

于 2013-06-27T20:02:35.390 回答
3

第二个示例创建一个env使用列表推导式命名的字典。

什么是字典?这是一个关联列表。考虑字典的一种方式是,它们就像数组,只是它们不是由数字索引,而是由其他东西索引。在这种情况下,它们由字符串索引,即环境变量的名称。

什么是列表理解?这是一种创建列表的方法。由该列表推导创建的列表是对、环境变量名称和该环境变量的值的列表。内置函数dict从这样的对列表中创建一个字典。

于 2013-06-27T20:05:49.893 回答