PyCharm:猴子修补的代码完成
我想知道是否可以让 PyCharm 支持猴子修补函数的代码完成?
我有以下课程:
class _PathExt(Path):
def ensure_exists(self):
if not self.exists():
if not self.parent.exists():
os.makedirs(self.parent.absolute(), exist_ok=True)
os.makedirs(self.absolute())
return self
def subdir(self, sub_name):
return Path(os.path.join(self.absolute(), sub_name))
然后我对其进行猴子修补:
def monkey_patch(from_type, to_type):
for name in [x for x in dir(from_type) if not x.startswith('_') and x not in dir(to_type)]:
value = from_type.__getattribute__(from_type, name)
if inspect.isfunction(value):
setattr(to_type, name, value)
monkey_patch(_PathExt, Path)
这是可以理解的,因为它是动态的,所以它不起作用,所以我然后尝试:
Path.subdir = _PathExt.subdir
但 PyCharm 仍然无法检测到它。这有可能吗?
编辑:
在这种特定情况下,我决定从 Path
派生我的类,然后使用 as
别名导入我的类,因此这是一个替代品,但我'我仍然想知道是否可以采取任何措施来支持 PyCharm 中的猴子修补。
I'm wondering if it's possible to get PyCharm to support code completion for monkey patched functions?
I have the following class:
class _PathExt(Path):
def ensure_exists(self):
if not self.exists():
if not self.parent.exists():
os.makedirs(self.parent.absolute(), exist_ok=True)
os.makedirs(self.absolute())
return self
def subdir(self, sub_name):
return Path(os.path.join(self.absolute(), sub_name))
Which I then monkey patch with:
def monkey_patch(from_type, to_type):
for name in [x for x in dir(from_type) if not x.startswith('_') and x not in dir(to_type)]:
value = from_type.__getattribute__(from_type, name)
if inspect.isfunction(value):
setattr(to_type, name, value)
monkey_patch(_PathExt, Path)
It's understandable that this wouldn't work as it's dynamic, so I then tried:
Path.subdir = _PathExt.subdir
But still PyCharm won't detect it. Is this possible at all?
Edit:
In this specific case I've decided to derive my class from Path
and then import my class with an as
alias, so it's a drop in replacement, but I'd still like to know if anything can be done to support monkey patching in PyCharm.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论