Skip to content

Type of the same class inside the class #3661

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

Closed
mrkaspa opened this issue Jul 5, 2017 · 3 comments
Closed

Type of the same class inside the class #3661

mrkaspa opened this issue Jul 5, 2017 · 3 comments
Labels

Comments

@mrkaspa
Copy link

mrkaspa commented Jul 5, 2017

I have a method that returns itself but it doesn't know the type of the class inside

class TcpFlow(object):

    def __init__(self) -> None:
        self.matches = []  # type: List[str]

    def __enter__(self) -> TcpFlow:
        return self

I got this error

Traceback (most recent call last):
  File "example/sample.py", line 2, in <module>
    from tcpflow import TcpFlow
  File "/Users/mrkaspa/code/py/tcpflow.py/tcpflow/__init__.py", line 1, in <module>
    from .tcpflow import TcpFlow
  File "/Users/mrkaspa/code/py/tcpflow.py/tcpflow/tcpflow.py", line 8, in <module>
    class TcpFlow(object):
  File "/Users/mrkaspa/code/py/tcpflow.py/tcpflow/tcpflow.py", line 16, in TcpFlow
    def __enter__(self) -> TcpFlow:
NameError: name 'TcpFlow' is not defined
@ilevkivskyi
Copy link
Member

In such cases you should put the name of class in quotes (this is called forward reference), like this:

class TcpFlow(object):
    def __enter__(self) -> 'TcpFlow':
        return self

@Garrett-R
Copy link

As of Python 3.7, you can now do:

from __future__ import annotations

class TcpFlow(object):
    def __enter__(self) -> TcpFlow:
        return self

(notice the quotes around the return type have been removed)

@johnthagen
Copy link
Contributor

johnthagen commented Dec 15, 2022

As of Python 3.11, you can now use the Self type to express the intent clearly and concisely:

from typing import Self

class TcpFlow:
    def __enter__(self) -> Self:
        return self

This new pattern can be applied to previous versions of Python using typing_extensions.Self backport.


Note that this removed the need to use:

from __future__ import annotations

which is important as the SC has tentatively accepted PEP 649, which indicates the future will be to move away from from __future__ import annotations.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

4 participants