Question

I have a project named automated_vertica in Eclipse PyDev, with following architecture :

automated_vertica
    src
        root
            __init__.py
            RequestHandler.py

RequestHandler.py is a module with a bunch of methods and nothing else.

__init__.py contains just two lines:

from root import RequestHandler
print('test')

When I run __init__.py in PyDev, Eclipse console reads test twice. If I remove the from root, it works just fine.

Can you please explain what I'm missing and what's happening here ?

EDIT: content of RequestHandler.py

'''
Created on Apr 23, 2014

@author: myname
'''
def FileToString(fileName): 
    f = open(fileName, 'r')
    result = f.read() 
    f.close()
    return result

def Flatten(listOfLists):
        return [value for sublist in listOfLists for value in sublist]
Was it helpful?

Solution

As root has an __init__ file, it's a module.

When you run a from module import.., it executes any code in that modules __init__.

And since your __init__ contains a print, that gets executed.

Since you're running __init__ directly (Which you shouldn't do btw), it's doing the following:

-> from root import RequestHandler
    -> root.__init__:
        -> import RequestHandler
        -> print("Test")
-> print("Test")

The __init__ is useful for checking presence of any modules, or fallbacks, or checking a python version.

For example, this __init__.py will not let any versions of Python less than 400 import the module:

import sys

if not hasattr(sys, "version_info") or sys.version_info < (400, 0):
    raise RuntimeError("root requires Python 400.0 or later.")

del sys

from root import RequestHandler
print("Test")

Let's hope it updates til the end of time then.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top