Skip to content

Implement PEP 810 (lazy imports) #3246

@HippoProgrammer

Description

@HippoProgrammer

Summary

Provide an implementation of the PEP 810 lazy-import feature added into Python 3.15.

What is the feature request for?

The core library

The Problem

Currently, there are very few ways to reasonably implement lazy-imports in Python (in stable releases) - however, there are situations in which such a method would be useful. For example, currently Pycord uses the fairly ubiquitous method of an if typing.TYPE_CHECKING statement to prevent runtime loading of modules solely required for static type checking. With lazy imports, said modules can simply be marked as lazily-imported, and will not be loaded at runtime. There are also other potential use cases for lesser-utilised sections of Pycord, maybe in voice-related libraries and such like - although lazy imports are not supported with from x import *, potentially restricting the implementation of this feature.

The Ideal Solution

Implement PEP 810, specifically in the backwards-compatible manner utilising the newly provided __lazy_modules__ global, as defined in the PEP:

Use the lazy_modules global for compatibility:

__lazy_modules__ = ['expensive_module', 'expensive_module_2']
import expensive_module
from expensive_module_2 import MyClass

The __lazy_modules__ attribute is a list of module name strings. When an import statement is executed, Python checks if the module name being imported appears in __lazy_modules__. If it does, the import is treated as if it had the lazy keyword (becoming potentially lazy). On Python versions before 3.15 that don’t support lazy imports, the __lazy_modules__ attribute is simply ignored and imports proceed eagerly as normal.

This allows Pycord to maintain its goal of compatibility with a wide range of Python versions, while also allowing improvements in this manner to be made before this change propagates through all of Pycord's supported versions.

The Current Solution

Given that this targets multiple issues, there are multiple current solutions: however, to give an example of the static type checking, using typing.TYPE_CHECKING as a safeguard in various modules.

Additional Context

Noting that PEP 810 is currently only implemented in the latest 3.15 pre-release, namely 3.15.0b1.

Metadata

Metadata

Assignees

No one assigned

    Labels

    feature requestNew feature requesttypingIs related to / changes python typing
    No fields configured for Feature.

    Projects

    Status
    Todo

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions