Skip to content

Explore PEP 563 (better conditional type imports) #1327

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
dlqqq opened this issue Apr 17, 2025 · 0 comments
Open

Explore PEP 563 (better conditional type imports) #1327

dlqqq opened this issue Apr 17, 2025 · 0 comments
Labels
enhancement New feature or request good first issue Good for newcomers

Comments

@dlqqq
Copy link
Member

dlqqq commented Apr 17, 2025

Problem

PEP 563 was adopted in Python 3.7, and may be able to make it easier for us to import types from other modules conditionally.

Modules can run this import to enable PEP 563:

from __future__ import annotations

This statement ensures that conditional type imports don't need to be surrounded in quotes when annotating a type. I will elaborate on what I mean by this in an example. Take this code:

from .persona_manager import PersonaManager

def get_manager() -> PersonaManager:
  pass

Here we are just using PersonaManager to annotate the type of this function, but this also imports the entire persona_manager module even though it is not used here.

We can make this a conditional type import:

from typing import TYPE_CHECKING
if TYPE_CHECKING:
  from .persona_manager import PersonaManager

def get_manager() -> PersonaManager:
  pass

However, this fails at runtime because the type annotations are somehow evaluated at runtime. This forces types from conditional imports to be surrounded in quotes:

...

def get_manager() -> 'PersonaManager':
  pass

With PEP 563, conditional type imports are slightly easier since the type no longer needs to be surrounded in quotes:

from __future__ import annotations
from typing import TYPE_CHECKING
if TYPE_CHECKING:
  from .persona_manager import PersonaManager

def get_manager() -> PersonaManager: # works at runtime too!
  pass

Additional context.

There are a couple of open questions, which is why I think we should explore first before taking action.

  • Does this have any impact beyond the jupyter_ai module? For example, does running from __future__ import annotations have any chance of breaking other extensions / packages in the environment?

  • Is there any way to enforce that import to ensure PEP 563 is followed?

@dlqqq dlqqq added enhancement New feature or request good first issue Good for newcomers labels Apr 17, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request good first issue Good for newcomers
Projects
None yet
Development

No branches or pull requests

1 participant