I’m not an expert on type hinting, but the standard way to do forward
references is to use a string.
class Spam:
def method(self, other:'Spam') -> 'Spam':
pass
In the future, that behaviour will be changed so that annotations will
no longer be evaluated at definition-time, so you can drop the quotes.
Starting in Python 3.7 you can say:
from __future__ import annotations
to postpone evaluation of annotations. Eventually that will become the
default. (3.10 or 3.11 I expect.) See the PEP for details:
https://www.python.org/dev/peps/pep-0563/
Your other question is an interesting one. You shouldn’t rely on
private types, and that includes any type defined in a private module.
Its private, and you can’t rely on it existing and you shouldn’t be
touching it at all, not even as a type hint.
However Python’s re module is not private, and the type of compiled
patterns is not private either. So its just a type:
from re import Pattern
If you don’t want to do the actual import, then treat it as a forward
reference. I think this would work, although to be honest I’m not sure
if type checkers understand dots:
def function(arg:'re.Pattern') -> str:
pass
I would hope that the third-party regex module defines a similar public
class, so you can do this:
from typing import Union
Pattern = Union['re.Pattern', 'regex.Pattern']
As I said, I’m not a type hinting expert, so it would be good if you
could reply here and let us know if this actually works.