将变量(带评估)导入 class 命名空间(即 self.varName)

Import variables (with evaluation) to class namespace (i.e. self.varName)

我有一个 python 文件 input.py。有评论以及空格和制表符的混合,只是为了很好的衡量标准。

# comment1 or header
name    =   "project1"
length  = 100.0 # comment2
width   = 20.0
area = length * width
circumference = 2*length + 2*width
        # orphaned comment

我想读入我的 class 结构中的变量,其中一些是从其他变量求值的,以便可以像 self.area:

一样访问它们
import importlib
class Project:     
    def __init__(self, inFile):
        self.inFile = inFile
        ## from self.inFile import * # definitely not gonna work! 
        importlib.import_module(inFile) # doesn't work either! 
p1 = Project(r"/home/feedme/input.py")
print p1.area

期望的示例输出:

2000.0 

除了 from something import * 通常不是一个好主意之外,我可以使用什么来以这种方式将变量带入 class?

编辑: 删除了关于导入名称为字符串的模块的附带问题,因为我自己已经找到了答案; importlib

我建议使用 runpy 模块。以下将在传递给 class 初始化程序的路径上执行 python 脚本,并将所有非 dunder 变量加载到实例字典中:

import runpy

class Project(object):

    def __init__(self, path):
        module = runpy.run_path(path)
        for k, v in module.items():
            if not k.startswith('__'):
                self.__dict__[k] = v

例如:

>>> project = Project('conf.py')
>>> project.area
2000.0