How exactly does from ... import ... work?

Suppose I have a file called randomFile.py which reads like this: class A: def __init__(self, foo): self.foo = foo self.bar = bar(foo) class B(A): pass class C(B): pass def bar(foo): return foo + 1 Suppose in another file in the same directory, I have another python program. from randomFile import C # some code When C has to be imported, B also has to be imported because it is the parent. Therefore, A also has to be imported. This also results in the function bar being imported. When from ... import ... is called, does Python follow all the references and import everything that is needed, or does it just import the whole namespace (making wildcard imports acceptable :O)? -- -Surya Subbarao

On Tue, Jan 5, 2016 at 4:32 PM, u8y7541 The Awesome Person <surya.subbarao1@gmail.com> wrote:
Suppose I have a file called randomFile.py which reads like this: class A: def __init__(self, foo): self.foo = foo self.bar = bar(foo) class B(A): pass class C(B): pass def bar(foo): return foo + 1
Suppose in another file in the same directory, I have another python program.
from randomFile import C
# some code
When C has to be imported, B also has to be imported because it is the parent. Therefore, A also has to be imported. This also results in the function bar being imported. When from ... import ... is called, does Python follow all the references and import everything that is needed, or does it just import the whole namespace (making wildcard imports acceptable :O)?
Not sure why this is on -ideas; explanations of how Python already works would more normally go on python-list. When you say "from X import Y", what Python does is, more-or-less: import Y X = Y.X del Y The entire file gets executed, and then one symbol from it gets imported into the current namespace. ChrisA

This list is for ideas about future Python (the language) enhancements. Please direct questions about how Python currently works to the tutor list: https://mail.python.org/mailman/listinfo/tutor/ -- ~Ethan~
participants (3)
-
Chris Angelico
-
Ethan Furman
-
u8y7541 The Awesome Person