Search code examples
pythonpycharmtype-hinting

Type hints for asyncio's Process class


I'm trying to type hint the Process class returned by asyncio.create_subprocess_exec() but am getting a weak warning (Accessing a protected member of a class or a module inspection) in PyCharm, using Python 3.10 as interpreter.

My code:

from asyncio.subprocess import Process
...
self.process: Process = await asyncio.create_subprocess_exec(
    *run_cmd,
    stdout=asyncio.subprocess.PIPE,
)

What is the Pythonic way of resolving this warning?


Solution

  • This happens because for some strange reason the Process class is not included in the asyncio.subprocess.__all__ list.

    When a module defines a specific __all__ list and you import names from that module that do not appear in that list, PyCharm issues a warning because it considers that to be similar to importing protected names (starting with one underscore _).

    Since PY-8656 PyCharm supports the noqa directives used by flake8 to exclude a line from linter checks.

    Therefore the simplest solution is to just add such a directive to the import line:

    from asyncio.subprocess import Process  # noqa
    
    process: Process
    ...
    

    This has no impact on the type hints with Process. It is still recognized as a type by any type checker and its (public) methods are still exposed and known.