[Python-checkins] peps: Discuss issue #105 and a solution.
guido.van.rossum
python-checkins at python.org
Thu May 7 17:22:31 CEST 2015
https://hg.python.org/peps/rev/06fbe54fcfe1
changeset: 5833:06fbe54fcfe1
user: Guido van Rossum <guido at python.org>
date: Thu May 07 08:22:27 2015 -0700
summary:
Discuss issue #105 and a solution.
files:
pep-0484.txt | 42 +++++++++++++++++++++++++++++++++++++++-
1 files changed, 41 insertions(+), 1 deletions(-)
diff --git a/pep-0484.txt b/pep-0484.txt
--- a/pep-0484.txt
+++ b/pep-0484.txt
@@ -473,6 +473,46 @@
def leaves(self) -> List['Tree']:
...
+A common use for forward references is when e.g. Django models are
+needed in the signatures. Typically, each model is in a separate
+file, and has methods that arguments whose type involves other models.
+Because of the way circular imports work in Python, it is often not
+possible to import all the needed models directly::
+
+ # File models/a.py
+ from models.b import B
+ class A(Model):
+ def foo(self, b: B): ...
+
+ # File models/b.py
+ from models.a import A
+ class B(Model):
+ def bar(self, a: A): ...
+
+ # File main.py
+ from a import A
+ from b import B
+
+Assuming main is imported first, this will fail with an ImportError at
+the line ``from models.a import A`` in models/b.py, which is being
+imported from models/a.py before a has defined class A. The solution
+is to switch to module-only imports and reference the models by their
+_module_._class_ name::
+
+ # File models/a.py
+ from models import b
+ class A(Model):
+ def foo(self, b: 'b.B'): ...
+
+ # File models/b.py
+ from models import a
+ class B(Model):
+ def bar(self, a: 'a.A'): ...
+
+ # File main.py
+ from a import A
+ from b import B
+
Union types
-----------
@@ -1127,7 +1167,7 @@
assert ImSet.add.__annotations__ == {'a': 'ImSet', 'return': 'List[ImSet]'}
-Such a ``__future__`` import statement will be proposed in a separate
+Such a ``__future__`` import statement may be proposed in a separate
PEP.
--
Repository URL: https://hg.python.org/peps
More information about the Python-checkins
mailing list