Python - when is 'import' required?

import, module, python

Solution

`import` is all about names -- mostly "bare names" that are bound at top level (AKA global level, AKA module-level names) in a certain module, say `mod2`. When you've done `import mod2`, you get the `mod2` namespace as an available name (top-level in your own module, if you're doing the `import` itself as top level, as is most common; but a local `import` within a function would make `mod2` a local variable of that function, etc); and therefore you can use `mod2.foobar` to access the name `foobar` that's bound at top level in `mod2`. If you have no need to access such names, then you have no need to `import mod2` in your own module.

Problem

mod1.py ``` import mod2 class Universe: def __init__(self): pass def answer(self): return 42 u = Universe() mod2.show_answer(u) ``` mod2.py ``` #import mod1 -- not necessary def show_answer(thing): print thing.answer() ``` Coming from a C++ background I had the feeling it was necessary to import the module containing the Universe class definition before the show_answer function would work. I.e. everything had to be declared before it could be used. Am I right in thinking this isn't necessary? This is duck typing, right? So if an import isn't required to see the methods of a class, I'd at least need it for the class definition itself and the top level functions of a module? In one script I've written, I even went as far as writing a base class to declare an interface with a set of methods, and then deriving concrete classes to inherit that interface, but I think I get it now - that's just wrong in Python, and whether an object has a particular method is checked at runtime at the point where the call is made? I realise Python is so much more dynamic than C++, it's taken me a while to see how little code you actually need to write! I think I know the answer to this question, but I just wanted to get clarification and make sure I was on the right track. UPDATE: Thanks for all the answers, I think I should clarify my question now: Does mod2.show_answer() need an import (of any description) to know that thing has a method called answer(), or is that determined dynamically at runtime?

Original source