0

I'm doing some kind of Python3 code generation, and I hope to generate strongly typed code, but I found it is hard to process with NoneType.

When I got an type reference on hand, I might want to generate it's representing code in type annotation in some case, and also might want to generate it's representing code as type reference at runtime code in some other case. But it's not consistant, in the first case, I need to generate code like None in context like f: int -> None, but in the second case, I have to generate code like type(None) in context like ty = type(None), I hope to use NoneType to make it consistent.

I found that there exists types.NoneType in some earlier subversion of Python3, but removed then, and in Python3.10 it is added back. So there are many Python3 subversions which doesn't export the NoneType from types.

Where is the NoneType located?

So, is there any way I can define a backport of NoneType so I can use it consistently and be compatibility with as much Python3 subversion as possible.

luochen1990
  • 3,689
  • 1
  • 22
  • 37

1 Answers1

0

This is my solution:

from typing_extensions import Protocol, TypeAlias

NoneType: TypeAlias = Literal[None]

I found that this works well on Python3.8 at runtime (means no exception will be thrown), and also works well with pyright/pylance (means can be recognized correctly when be static analyzed).

Since Literal is introduced in Python3.8 in pep586, it should also works well in Python3.9 or later. And since typing_extensions also export Literal, so it is very promising that this can works on Python3.7 or even former.

luochen1990
  • 3,689
  • 1
  • 22
  • 37