Python 动态属性和 mypy [英] Python dynamic properties and mypy
问题描述
我正在尝试将一些函数屏蔽为属性(通过在这里并不重要的包装器)并将它们动态添加到对象中,但是,我需要代码完成和 mypy 才能工作.
I'm trying to mask some functions as properties (through a wrapper which is not important here) and add them to the object dynamically, however, I need code completion and mypy to work.
我想出了如何动态添加属性(通过元类或简单地在构造函数中),但我遇到的问题是 mypy 没有选择它(IDE 也没有).
I figured out how to add a property dynamically (either through a metaclass or simply in constructor), but the problem I have is mypy doesn't pick it up (and neither does the IDE).
一种解决方法是定义一个具有相同名称/类型的属性,但我真的不喜欢这种方法(太多代码、静态属性集、重复).
One workaround is to define an attribute with the same name/type, but I really don't like this approach (too much code, static set of attributes, repetition).
有更好的方法吗?
class Meta(type):
def __new__(cls, clsname, bases, dct):
def prop(self) -> int:
return 1
inst = super(Meta, cls).__new__(cls, clsname, bases, dct)
inst.dynprop=property(prop)
return inst
class Foo(metaclass=Meta):
dynprop=int #this works, but I don't want it
class Bar(metaclass=Meta):pass
def somefunc(s:str):
print(s)
foo=Foo()
bar=Bar()
somefunc(foo.dynprop) #this is ok
somefunc(bar.dynprop) #meta.py:24: error: "Bar" has no attribute "dynprop"
推荐答案
修复您的 IDE?:-).在 Python 中,总会有静态分析无法进行的极端情况.在这种情况下,您获得了本应帮助您挡路的工具.
Fix your IDE? :-). In Python there will always be corner cases where static analysis can't go . In this case you got the tools that ere supposed to be helping you getting in your way.
IDE 或 Mypy 无法在不运行代码的情况下查找这些动态属性.我知道有一些 IDE,至少在过去,它们实际上是通过导入一个模块来实现自动完成的——但这也会引发一系列附带影响.
There is no way for either the IDE or Mypy to find about these dynamic attributes without running the code. I know there are IDEs, that at least in the past, resorted to actually importing a module to have auto-complete - but that also can trigger a host of collateral effects.
我想说,为了拥有动态代码,您将不得不在没有这些工具的情况下生活 - 以添加带有不检查此"标记样式的注释.根本不可能自动完成.
I'd say you will have to live without these tools in order to have your dynamic code - to the point of adding comments with the "don't check this" markup style. Autocomplete can't be possible at all.
这篇关于Python 动态属性和 mypy的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!