HaggarTheHorrible
HaggarTheHorrible

Reputation: 7403

After Python import, call to a definition is generating the NameError

I'm new to python and I was trying to do the following:

I have a folder called app and this folder has two files: main.py and init.py

The

main.py

def generate_report(x1, x2):
    print "Generating report..."
    print x1
    print x2 

if __name__ == "__main__":
    print "Running: main.py..."

    generate_reports(1, 2)

    print "Done!"

else:
    print "Imported: main.py..."

The

__init__.py

import main

Now in my console if I do:

import app

I get:

Imported: main.py...

Then if I try to do:

generate_report(1, 2)

I get the following error:

NameError: name 'generate_report' is not defined

Upvotes: 2

Views: 102

Answers (1)

Veky
Veky

Reputation: 2745

There are two different approaches to module namespaces in Python. In one, you do import blah and then access blah's elements with blah.spam. In another, you say from blah import spam (or *) and then access blah's elements directly by name.

The problem is, you have to make that decision on every level: if you have a package, you have two such decisions to make: how your script imports package (app in your case), and how your app's __init__.py imports main (btw a horrible name for a module;P).

So, one solution is to write

from app import main

in your __init__.py, and

from app import generate_report

in your script, and another is to write

app.main.generate_report

in your script. Of course, there are two other ways, where some import is direct, and some is fromed.

Upvotes: 4

Related Questions