[Python-checkins] peps: Add typing.TYPE_CHECKING to PEP 484.
guido.van.rossum
python-checkins at python.org
Wed Jun 8 14:13:54 EDT 2016
https://hg.python.org/peps/rev/9759b59479c2
changeset: 6358:9759b59479c2
user: Guido van Rossum <guido at python.org>
date: Wed Jun 08 11:13:41 2016 -0700
summary:
Add typing.TYPE_CHECKING to PEP 484.
files:
pep-0484.txt | 29 ++++++++++++++++++++++++++++-
1 files changed, 28 insertions(+), 1 deletions(-)
diff --git a/pep-0484.txt b/pep-0484.txt
--- a/pep-0484.txt
+++ b/pep-0484.txt
@@ -983,6 +983,31 @@
``"".join(reversed(sys.platform)) == "xunil"``.
+Runtime or type checking?
+-------------------------
+
+Sometimes there's code that must be seen by a type checker (or other
+static analysis tools) but should not be executed. For such
+situations the ``typing`` module defines a constant,
+``TYPE_CHECKING``, that is considered ``True`` during type checking
+(or other static analysis) but ``False`` at runtime. Example::
+
+ import typing
+
+ if typing.TYPE_CHECKING:
+ import expensive_mod
+
+ def a_func(arg: 'expensive_mod.SomeClass') -> None:
+ a_var = arg # type: expensive_mod.SomeClass
+ ...
+
+(Note that the type annotation must be enclosed in quotes, making it a
+"forward reference", to hide the ``expensive_mod`` reference from the
+interpreter runtime. In the ``# type`` comment no quotes are needed.)
+
+This approach may also be useful to handle import cycles.
+
+
Arbitrary argument lists and default argument values
----------------------------------------------------
@@ -1174,7 +1199,7 @@
NewType helper function
------------------------
+=======================
There are also situations where a programmer might want to avoid logical
errors by creating simple classes. For example::
@@ -1644,6 +1669,8 @@
forward references (which are given as string literals) as expressions
in the context of the original function or method definition.
+* TYPE_CHECKING, ``False`` at runtime but ``True`` to type checkers
+
Types available in the ``typing.io`` submodule:
* IO (generic over ``AnyStr``)
--
Repository URL: https://hg.python.org/peps
More information about the Python-checkins
mailing list