Mypy: Type of the same class inside the class

Created on 5 Jul 2017  路  2Comments  路  Source: python/mypy

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
question

Most helpful comment

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

All 2 comments

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

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)

Was this page helpful?
0 / 5 - 0 ratings