Home >Backend Development >Python Tutorial >How Can I Type Hint a Method's Enclosing Class in Python?

How Can I Type Hint a Method's Enclosing Class in Python?

Barbara Streisand
Barbara StreisandOriginal
2024-12-19 11:17:09580browse

How Can I Type Hint a Method's Enclosing Class in Python?

Type Hinting a Method with Enclosing Class Type

In Python, representing the type of a method's enclosing class can be achieved through various methods depending on the Python version.

Python 3.7 with 'from future import annotations'

By enabling the "deferred evaluation of annotations" feature with from __future__ import annotations, annotations can be stored as strings and evaluated asynchronously.

from __future__ import annotations

class Position:
    def __add__(self, other: 'Position') -> 'Position':
        ...

Python 3.11 with 'from typing import Self'

Python 3.11 introduces the Self type to represent the enclosing class type.

from typing import Self

class Position:
    def __add__(self, other: Self) -> Self:
        ...

Python <3.7

For Python versions prior to 3.7, strings are used to indicate the enclosing class type.

class Position:
    def __add__(self, other: 'Position') -> 'Position':
        ...<p><strong>Handling Forward References</strong></p>
<p>PEP 484 specifies that forward references should be represented as strings until they are fully defined.</p>
<pre class="brush:php;toolbar:false">class Tree:
    def __init__(self, left: 'Tree', right: 'Tree'):
        ...

Alternatives

Avoid using dummy definitions of the enclosing class or monkey-patching the class to add annotations, as these approaches may result in incorrect annotation behavior.

The above is the detailed content of How Can I Type Hint a Method's Enclosing Class in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn