4

I have a 3rd-party web-framework which has type hints in some of its code. I can not control the code of the said framework

Suppose I have following piece

from framework import web
...


class UserPosts(web.WebView):
    async def get(self):
        user_id = await self.request.user_dict['id']
        ...
    

web.WebView class has type hints in its code and request attribute is marked as an instance of a specific class which doesn't have user_dict attr in definition because it is a dict that my custom made middleware dynamically attaches to the request instance.

I want to provide type hint for user_dict but I don't understand how this can be approached.

Can someone help me with a tip about the right direction?

Thanks.

S.S.J
  • 353
  • 1
  • 7
  • Could you provide some more code, enough to create a minimal reproducible example? – BrokenBenchmark Apr 22 '22 at 03:24
  • @BrokenBenchmark I am not sure that I can post it there as minimal example would require to create about 20 files and upload the 3rd party framework somewhere on the Internet – S.S.J Apr 22 '22 at 03:30

1 Answers1

0

Define a new class, and override the ctor within that class:

class MyWebView(web.WebView):

    def __init__(self, ...):
        super().__init__( ... )

So far nothing has changed.

Now adjust the constructor so it uses proper type hints, add logging and parameter validation to taste, the world is your oyster!

J_H
  • 17,926
  • 4
  • 24
  • 44
  • Well, this might be the way to go but I doubt I can convince to touch code of 500+ files just to make pyright/mypy work well. I guess it would be easier to just abandon the idea of using typechecker :-( Anyway, thanks a lot for your prompt response – S.S.J Apr 22 '22 at 03:32
  • Oh, you have many classes to worry about. Well, you can always write a source code parser. https://docs.python.org/3/library/ast.html Take a look at how folks produce type hint stub files for large code bases -- in some ways your problem sounds similar to that, which is a pretty well understood task at this point. – J_H Apr 22 '22 at 03:49
  • Is there maybe an opportunity to monkey patch the 3rd-party library at the proper moment? That is, after importing it but prior to the type hint analysis? – J_H Apr 22 '22 at 03:51