亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

從 Python 3 中的代碼對象中提取所有常量

從 Python 3 中的代碼對象中提取所有常量

肥皂起泡泡 2022-01-18 21:17:46
我想提取函數中使用的所有常量。在Python 2.7中,我可以遍歷函數的co_constsin__code__并提取所有字符串。例如, Python 2.7>>> def func():...:     return 'foo' if True else ('bar',)>>> print(func.__code__.co_consts)(None, 'foo', 'bar', ('bar',)) # no need to look into the tuple as 'bar' is available outside it as well.這會給我'foo'和'bar'預期的那樣。但是,在 中Python 3.7,代碼對象'bar'只包含在元組內部。蟒蛇 3.7>>> print(func.__code__.co_consts)(None, True, 'foo', ('bar',))這意味著我還需要查看 co_consts 中的元組。我的困惑是內部是否可以有更多級別的嵌套co_consts?
查看完整描述

2 回答

?
哈士奇WWW

TA貢獻1799條經驗 獲得超6個贊

然后,您可以遞歸地遍歷co_consts元組:


def x():

    return {

        "y": ("bla" + "ble", ("blo", ["blu", "blip"])),

        ("x", "z"): "blup",

        True: False,

        42: "hello" * 10,

        None: 4 + 1j,

    }



def get_consts(func):

    def walk(cell):

        if isinstance(cell, tuple):

            for item in cell:

                yield from walk(item)

        else:

            yield cell


    yield from walk(func.__code__.co_consts)



for const in get_consts(x):

    print(const)

印刷


None

blable

blo

blu

blip

blup

False

hellohellohellohellohellohellohellohellohellohello

(4+1j)

y

x

z

True

42

None

常量的順序可能與原始源中的不同;它們確實對應于反匯編中的順序:


  5           0 LOAD_CONST               1 ('blable')

              2 LOAD_CONST               2 ('blo')

              4 LOAD_CONST               3 ('blu')

              6 LOAD_CONST               4 ('blip')

              8 BUILD_LIST               2

             10 BUILD_TUPLE              2

             12 BUILD_TUPLE              2


  6          14 LOAD_CONST               5 ('blup')


  7          16 LOAD_CONST               6 (False)


  8          18 LOAD_CONST               7 ('hellohellohellohellohellohellohellohellohellohello')


  9          20 LOAD_CONST               8 ((4+1j))

             22 LOAD_CONST               9 (('y', ('x', 'z'), True, 42, None))

             24 BUILD_CONST_KEY_MAP      5

             26 RETURN_VALUE

編輯:如果您需要源中的原始字符串,則需要使用該ast模塊:


import ast

import inspect



class ConstantGatherer(ast.NodeVisitor):

    def __init__(self):

        super().__init__()

        self.consts = []


    def visit_Str(self, node):

        self.consts.append(node.s)


    def visit_Num(self, node):

        self.consts.append(node.n)



cg = ConstantGatherer()

cg.visit(ast.parse(inspect.getsource(x)))

print(cg.consts)

輸出


['y', 'x', 'z', 42, 'bla', 'ble', 'blo', 'blu', 'blip', 'blup', 'hello', 10, 4, 1j]


查看完整回答
反對 回復 2022-01-18
?
呼啦一陣風

TA貢獻1802條經驗 獲得超6個贊

如何使用以下代碼中3的函數從函數中獲取 const 參數值?finspect


def l2_norm(x, axis):

  print("l2_norm", x, axis)


f = lambda x: l2_norm(x, axis=3)


查看完整回答
反對 回復 2022-01-18
  • 2 回答
  • 0 關注
  • 229 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號