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 > >
