简体   繁体   English

如何在不导入的情况下获取python模块中定义的所有变量?

[英]How to get all of the variables defined in a python module without imports?

For example, if I have the following structure: 例如,如果我具有以下结构:

base.py base.py

foo = 1
bar = 2

extended.py 扩展名

from base import *

baz = 3
qux = 4

I'm looking to get only the variables defined in extended.py. 我希望仅获取在extended.py中定义的变量。


I've tried using dir and 'inspect', 我试过使用dir和'inspect',

import inspect
import extended
vars = dir(extended)
members = inspect.getmembers(extended)

but this gives vars = ['bar', 'baz', 'foo', 'qux', ...] and members=[('bar', 2), ('baz', 3), ('foo', 1), ('qux', 4), ...] 但这使vars = ['bar', 'baz', 'foo', 'qux', ...]vars = ['bar', 'baz', 'foo', 'qux', ...] members=[('bar', 2), ('baz', 3), ('foo', 1), ('qux', 4), ...]

Is there anyway to actually do this in python, given this structure of how extended.py is defined? 鉴于定义了extended.py的这种结构,在Python中是否有实际执行此操作的方法?

I decided to give this a bash for personal interest, it will probably work for what you want, I havent' looked at how more complex assignments work eg slice assignments etc: 我决定为个人兴趣而设置这个bash,它可能会满足您的需求,我还没有研究更复杂的任务的工作方式,例如切片任务等:

import ast

with open("extended.py") as f:
    code = f.read()

tree = ast.parse(code)

assignments = [
    node
    for node in ast.walk(tree)
    if isinstance(node, ast.Assign)
]

target_variables = set()
for a in assignments:
    print("{}: {}".format(a, ast.dump(a)))
    for target in a.targets:
        target_variables.add(target.id)

print("Found {} assignments to these variable names:".format(len(assignments)))
print(target_variables)

I found a somewhat simple way of doing it, that is possible not perfect, but it will work: 我发现了一种比较简单的方法,虽然可能并不完美,但是可以正常工作:

def find_names_of_module(module):
    code = compile(open(module.__file__).read(), module.__name__, "exec")
    return code.co_names

Sadly this does also return modules imported with from module import * or import module and also functions. 可悲的是,这确实还会返回from module import *import module以及功能。 You could filter it to not have modules and functions if you don't want them. 如果不需要它们,可以对其进行过滤以使其不具有模块和功能。

If you need only the top-level variable names, here is a tweak of Tom Dalton answer that only includes top level variables: 如果只需要顶级变量名,这是汤姆·道尔顿(Tom Dalton)答案的一项调整,仅包含顶级变量:

def find_names_of_module(module):

    with open(module.__file__) as f:
        code = f.read()

    tree = ast.parse(code)

    assignments = (node for node in tree.body if isinstance(node, ast.Assign))
    return {target.id for a in assignments for target in a.targets}

If you can change the structure I would go with this solution: 如果您可以更改结构,则可以使用以下解决方案:

base.py base.py

foo = 1
bar = 2

extension.py extension.py

baz = 3
qux = 4

extended.py 扩展名

from base import *
from extension import *

Otherwise, I'm not sure if this code actually works and there must be a better way but you can use the difference between modules members: 否则,我不确定此代码是否确实有效,并且必须有更好的方法,但是您可以使用模块成员之间的区别:

import inspect
import base
import extended
base_members = inspect.getmembers(base)
ext_members = inspect.getmembers(extended)
ext_only_members = [member for member in ext_members if member not in base_members]

Since the list content is not hashable you can't use a set to get the diff. 由于列表内容不可散列,因此不能使用集合来获取差异。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Python:如何获取在另一个模块中定义的所有局部变量 - Python: How to get all of the local variables defined in another module Python跨模块变量和导入 - Python cross module variables and imports 如何获取python中function中定义的所有局部变量? - How to get all the local variables defined inside the function in python? ansible 中有没有办法让我的 python 脚本获取所有定义的变量而不将它们全部传入? - is there a way in ansible for my python script to get all the variables that are defined without passing them all in? 如何提取然后引用python模块中定义的变量? - How to extract and then refer to variables defined in a python module? 获取 Python 模块中定义的所有函数 - Get all defined functions in Python module 如何在不更改导入的情况下将Python 3模块更改为软件包? - How to change a Python 3 module to a package without changing the imports? 在python中,如何打印导入模块中定义的所有函数的文档字符串,而无需导入模块本身导入的函数? - In python, how to print the docstrings of all functions defined in an imported module, without the functions that the imported module itself imported? Python导入:导入没有.py扩展名的模块? - Python imports: importing a module without .py extension? 如何在Python中列出我自己定义的所有变量,不包括导入的变量? - How to list all variables defined by myself in Python, excluding imported variables?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM