Skip to content
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

Proposal: OOP Interface Support in Python #130992

Closed
programadorLhama opened this issue Mar 9, 2025 · 1 comment
Closed

Proposal: OOP Interface Support in Python #130992

programadorLhama opened this issue Mar 9, 2025 · 1 comment
Labels
type-feature A feature request or enhancement

Comments

@programadorLhama
Copy link

programadorLhama commented Mar 9, 2025

Feature or enhancement

Proposal:

Abstract

This proposal suggests introducing an official way to define and enforce interfaces in Python. The proposed solution utilizes metaclasses to ensure that derived classes implement interface methods with identical signatures, improving code robustness and maintainability.

Motivation

Python currently lacks a built-in mechanism to enforce method signatures in interfaces. While the abc module allows for abstract base classes (ABCs), it does not verify method signatures, leading to potential runtime errors when method signatures do not match expectations.

This proposal introduces an InterfaceMeta metaclass that ensures derived classes implement all required interface methods with the correct signatures. This helps developers detect signature mismatches early, enhancing code reliability.

Specification

A new Interface class will be introduced, using the InterfaceMeta metaclass. Any class inheriting from Interface must implement all defined methods with the same signature.

from abc import ABCMeta
import inspect

class InterfaceMeta(ABCMeta):
    """Metaclass to force implementation of methods in derived classes with the same signature."""
    
    def __new__(mcs, name, bases, namespace):
        if bases:  # Ensure we are checking derived classes, not the base interface
            for base in bases:
                if isinstance(base, InterfaceMeta):
                    for attr_name, attr_value in base.__dict__.items():
                        if callable(attr_value) and not attr_name.startswith('__'):
                            if attr_name not in namespace:
                                raise TypeError(
                                    f"Class '{name}' must implement method '{attr_name}' of interface '{base.__name__}'"
                                )
                            
                            base_signature = inspect.signature(attr_value)
                            derived_signature = inspect.signature(namespace[attr_name])
                            
                            if base_signature != derived_signature:
                                raise TypeError(
                                    f"Method '{attr_name}' in class '{name}' does not match the interface signature.\n"
                                    f"Expected: {base_signature}\n"
                                    f"Got: {derived_signature}"
                                )
        return super().__new__(mcs, name, bases, namespace)

class Interface(metaclass=InterfaceMeta):
    """Base class for all interfaces."""
    pass

Example Usage

class MyInterface(Interface):
    def method(self, x: int) -> str:
        pass

class ValidImplementation(MyInterface):
    def method(self, x: int) -> str:
        return str(x)

class InvalidImplementation(MyInterface):
    def method(self, x):  # Missing return annotation
        return str(x)

# Raises TypeError: "Method 'method' in class 'InvalidImplementation' does not match the interface signature."
# Expected: (self, x: int) -> str
# Got: (self, x)

Backward Compatibility

This proposal introduces a new interface enforcement mechanism and does not affect existing ABCs or classes. It is fully backward-compatible with current Python functionality.

Alternatives Considered

  1. Using Abstract Base Classes (ABCs): While ABCs enforce method existence, they do not verify method signatures, making them less strict than this approach.

  2. Type Hints & Static Analysis (e.g., mypy): While static analysis tools can detect type mismatches, they do not enforce runtime constraints, which this proposal aims to achieve.4.

Open Questions

  • Should this functionality be integrated into the abc module or remain as a standalone implementation?

  • Should additional enforcement (e.g., return type enforcement) be included?

Conclusion

This proposal enhances Python's object-oriented capabilities by introducing runtime-verified interfaces. By enforcing method signatures, it reduces bugs and improves maintainability in large-scale applications.

Has this already been discussed elsewhere?

No response given

Links to previous discussion of this feature:

No response

Linked PRs

@programadorLhama programadorLhama added the type-feature A feature request or enhancement label Mar 9, 2025
@programadorLhama programadorLhama changed the title Proposal: Interface Support in Python Proposal: OOP Interface Support in Python Mar 9, 2025
@ZeroIntensity
Copy link
Member

This needs to be discussed this on DPO first, but please don't use ChatGPT to generate feature proposals.

@ZeroIntensity ZeroIntensity closed this as not planned Won't fix, can't repro, duplicate, stale Mar 9, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
type-feature A feature request or enhancement
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants