[英]Is there a way to detect the order of a module's globals() in python?
python模塊中使用了一些全局變量:
ImFirst = 1
ImSecond = 2
AndImThird = "three"
globals()給出了這些名稱和值的字典,但不幸的是,它不是OrderedDict(顯然,因為globals()早於collections模塊)。
有沒有辦法獲得全局名稱在模塊中出現的順序?
您可以使用tokenize.generate_tokens來按照令牌名稱出現的順序收集數據。
例如,如果將此文件另存為/tmp/test.py
並運行python /tmp/test.py
,它將讀取自己的代碼並報告全局變量出現的順序:
import tokenize
import io
import token
import collections
import itertools
class Token(collections.namedtuple('Token', 'toknum tokval start end line')):
@property
def tokname(self):
return token.tok_name[self.toknum]
ImFirst = 1
ImSecond = 2
AndImThird = "three"
if ImSecond:
ImFourth = 4.0
seen = set()
order = []
with open('/tmp/test.py', 'r') as f:
for tok in itertools.starmap(Token, tokenize.generate_tokens(f.readline)):
if tok.tokname == 'NAME' and tok.tokval not in seen:
seen.add(tok.tokval)
order.append(tok.tokval)
order = [name for name in order if name in globals()]
print(order)
產量
['tokenize', 'io', 'token', 'collections', 'itertools', 'Token', 'ImFirst', 'ImSecond', 'AndImThird', 'ImFourth', 'seen', 'order', 'f', 'tok', 'name']
感謝上面的eryksun的評論,我深入到sys._getframe()的“屬性樹”中,
顯然,所有全局名稱(按代碼出現的順序)都存在於:
sys._getframe().f_code.co_names
它還包含未定義的變量,但是將此信息與globals()結合使用就可以了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.