python / python/mypy

Add typed attribute to third party class.

Open
#9,823 1 comment 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

feature
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Feature

I would like to be able to add a (typed) attribute to a third-party class instance.

To give a specific example, Flask's current_app, and Flask-AppBuilder. Some example code:

    def my_view(self):
        reveal_type(current_app.appbuilder)
        if current_app.appbuilder.sm.has_access(...):
            ...

The reveal_type here shows Any: airflow/www/views.py:850: note: Revealed type is 'Any'

Things I tried:

  1. To add a typed attribute myself:

    if TYPE_CHECKING:
        current_app.appbuilder = AppBuilder(None)
        reveal_type(current_app.appbuilder)
    

    Didn't work: airflow/www/views.py:115: note: Revealed type is 'Any'

  2. A partial type stub file

    I could use stubgen etc to create a stub file for all of flask and then edit the type in flask.globals, but this presents a maintenance burden that I don't want (keeping it in sync).

    I searched for any way I could to have a "partial" stub file -- if I could have a stubs/flask/globals.pyi with out neededing all the rest of the type stubs for this module, but couldn't get it working - likely not supported.

Pitch

I don't know what the feature would look like, but for the flask ecosystem it is fairly common to add properties on to the global flask object, or the g global variable, and I would love to be able to type-check my use of them, without needing to cast it at each use.

This issue is mostly a request for help/ "is there any sensible way of doing this?"

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reproducing the reveal_type results in airflow/www/views.py:850 and the TYPE_CHECKING attempt around line 115. Review how Flask's flask.globals types and stubgen handle third-party attributes. Done means the issue has a documented, maintainable approach or a clearly scoped type-checker feature for typing such attributes without a full replacement stub.

Written by the indexing model from the issue text.

Assessment

Tech stack
flask, python
Domain
tooling
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.