pylint如何在argparse中不引发无成员消息?

时间:2019-06-06 05:22:30

标签: python argparse pylint

我写了这样的代码。

from argparse import Namespace

class Config(Namespace): 
    def __init__(self, filename):
        config = yaml.load(open(filename, 'r'))

        super(Config, self).__init__(**config)

config = Config('some/path/where/yaml/file/exist')

print(config.some_attr)

然后pyline发出这样的无成员警告。

Instance of 'Config' has no 'some_attr' member pylint(no-member)

但是argparse方法中的某些方法不会引发无成员警告。

parser = argparse.ArgumentParser("test")
parser.add_argument('--config', type=str, default='config')
args, _ = parser.parse_known_args()

args.test # no warning
args.config # no warning

此代码不会在pylint中发出任何警告。

我很好奇,所以我看了一下github中的相应代码。但是ArgumentParser.parse_knwon_args的第一个返回值也是命名空间对象。

如何解决自定义Config类未引发警告消息的问题?我不想在代码块中插入“#pylint:disable = no-member”。模块(类)中有解决方案吗?

1 个答案:

答案 0 :(得分:0)

您可以定义一个__getattribute__函数,该函数将“安全”地从类中获取属性,而pylint将不再抱怨。

class MyAttributeClass:
    def __getattribute__(self, name):
        object.__getattribute__(self, name)

请注意,这意味着pylint不会检测到对将永远不存在的成员的引用,因此错误可能会以这种方式潜入您的代码中。仅将其用于期望具有动态属性的类。