Isn't this simply because cars is not imported into __init__.py?

By the second time you run print_stuff(), you have imported both the
function in __init__ and the module that it references?

On Wed, Aug 29, 2012 at 11:29 AM, John Goodleaf <[email protected]> wrote:

> Okay, that was vague. Think of __init__.py as the package initializer.
> When you call the package, or any module resident therein, the initializer
> runs. So basically, any time you call something in the foo namespace, the
> things in __init__.py are available to the caller.
>
> --
> John Goodleaf
>
> On Wednesday, August 29, 2012 at 11:20 AM, John Goodleaf wrote:
>
>  The __init__.py file marks the contents of the directory as a package.
> Its code is executed when you reference the package.
>
> --
> John Goodleaf
>
> On Wednesday, August 29, 2012 at 11:17 AM, Leo Shklovskii wrote:
>
> Here's a fun question for the python lovers in the crowd. We ran into some
> unexpected behavior in our code and don't have a good explanation for why
> it
> happens.
>
> We've reduced it down to a super simple test case with three files:
>
> test.py
> --------
> import foo
> try:
> foo.print_stuff()
> except NameError:
> print 'expected NameError'
> import foo.cars
> foo.print_stuff() # why no NameError?
>
> foo/__init__.py
> ---------
> def print_stuff():
>  print cars.__file__
>
> foo/cars.py
> ---------
> def honk():
> pass
>
> Why doesn't the second call to print_stuff() raise a NameError? Why does
> importing something in test.py add it to the foo module's namespace?
>
> --
> --Leo
>
>
>
>

Reply via email to