python / python/mypy

Replace implicit reexport with explicit

Open
#16,597 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

feature topic-implicit-reexport
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Feature

I would like to create a way to explicitly suppress a specific implicit export.

Pitch

I am working with a wrapper library that attempts to unify an interface between multiple backends. So for example it does something like this:

# my_lib/foo.py

from . import BACKEND_A, BACKEND_B

if BACKEND_A:
    from lib_a.foo import *

    Confabulator.bar = Confabulator.baz

elif BACKEND_B:
    from lib_b.foo import *

The implicit export via star-import here is helpful because there are a lot of classes to import, more may be added, and most of them don't need to be modified like this at all.

Unfortunately this causes some minor problems with typing - I get an attr-defined error depending on the installed backend:

from my_lib.foo import Confabulator
c = Confabulator()
reveal_type(c)  # revealed type is lib_a.foo.Confabulator
c.bar()  # raises an [attr-defined] error

At first I thought this was an issue with adding class attributes after definition (rejected in #5363), but it's also a problem if I try to instead to subclass and re-assign. I think the implicit re-export is getting in the way of redefining the class.

My initial thought on how to achieve this would be to allow from lib_a.foo import Confabulator as _Confabulator after the from lib_a.foo import * to kind of undo the implicit export. I poked around in the code a bit but have not figured out the best way to do this yet. I do worry this would be a breaking change, however. I am open to any other suggestions or workarounds!

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 wrapper example with mypy, including the star import, renamed import, and subclassing alternatives described in the issue. Trace how implicit re-exports and redefinitions are analyzed. Done means a supported way to suppress one implicit export, with typing behavior covering the backend-dependent Confabulator example and no unintended breaking changes.

Written by the indexing model from the issue text.

Assessment

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.