Python dynamic properties and mypy

2024/10/5 11:22:40

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.

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).

Is there a better way?

class Meta(type):def __new__(cls, clsname, bases, dct):def prop(self) -> int:return 1inst = super(Meta, cls).__new__(cls, clsname, bases, dct)inst.dynprop=property(prop)return instclass Foo(metaclass=Meta):dynprop=int #this works, but I don't want itclass Bar(metaclass=Meta):passdef 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"
Answer

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.

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.

https://en.xdnf.cn/q/70492.html

Related Q&A

Flask-login: remember me not working if login_managers session_protection is set to strong

i am using flask-login to integrate session management in my flask app. But the remember me functionality doesnt work if i set the session_protection to strong, however, it works absolutely fine if its…

Does any magic happen when I call `super(some_cls)`?

While investigating this question, I came across this strange behavior of single-argument super:Calling super(some_class).__init__() works inside of a method of some_class (or a subclass thereof), but …

How to get unpickling to work with iPython?

Im trying to load pickled objects in iPython.The error Im getting is:AttributeError: FakeModule object has no attribute WorldAnybody know how to get it to work, or at least a workaround for loading obj…

Basic questions about nested blockmodel in graph-tool

Very briefly, two-three basic questions about the minimize_nested_blockmodel_dl function in graph-tool library. Is there a way to figure out which vertex falls onto which block? In other words, to ext…

How to get multiple parameters with same name from a URL in Pylons?

So unfortunately I find myself in the situation where I need to modify an existing Pylons application to handle URLs that provide multiple parameters with the same name. Something like the following...…

Kivy: Access configuration values from any widget

Im using kivy to create a small App for computer aided learning.At the moment I have some problems with accessing config values. I get the value withself.language = self.config.get(basicsettings, langu…

Multiprocessing with threading?

when I trying to make my script multi-threading, Ive found out multiprocessing,I wonder if there is a way to make multiprocessing work with threading?cpu 1 -> 3 threads(worker A,B,C) cpu 2 -> 3 …

Pandas Groupby Unique Multiple Columns

I have a dataframe.import pandas as pd df = pd.DataFrame( {number: [0,0,0,1,1,2,2,2,2], id1: [100,100,100,300,400,700,700,800,700], id2: [100,100,200,500,600,700,800,900,1000]})id1 id2 nu…

OpenCV Error: Assertion failed when using COLOR_BGR2GRAY function

Im having a weird issue with opencv. I have no issues when working in a jupyter notebook but do when trying to run this Sublime.The error is: OpenCV Error: Assertion failed (depth == CV_8U || depth == …

matplotlib 1.3.1 has requirement numpy=1.5, but youll have numpy 1.8.0rc1 which is incompatible

Im executing bellow command in Mac (High Sierra) as a part of getting started with pyAudioAnalysis.pip install numpy matplotlib scipy sklearn hmmlearn simplejson eyed3 pydub Im getting following error…