简体   繁体   中英

Python module order of execution

I have a normally structured Python program with import statements, class definitions, other routines, and some "main" statements that invoke methods in the classes (in that order). a print statement after the imports prints "ok"

Python 2.7.2

I am getting a nameError in a class method.

print >> common, ...

NameError: 'common' is not defined

common is used earlier in the same method, but the earlier references occasioned no errors.

common is used in many methods - moving this method physically has no effect: the error is still on the same line in this method.

The error occurs before the method is called, and before any of the "main" statements are executed. Putting return as the first executable statement in the method has no effect. This is all apparently happening at class definition time.

If I comment out the print >> common statements, I get a different NameError in the same method.

I have no idea how I can get a NameError inside a method at 'definition time'.

Any ideas? The method is below:

x = z ** 2 below is supposed to generate a NameError: there is no z. A print statement just after all the function definitions is not executed.

"""code below"""
 @classmethod
    def show_role_map(cls):
        """show jobs within roles, with total days, with percents of totals"""

        return
        raise ZeroDivisionError
        return

        print >> common, "xyzzy"

        x = z ** 2

        p       = Performance("Traveler: show_role_map")
        print   "\tshow_role_map"
        roles   = cls.role_map.keys()
        roles.sort()
        header  ("Qualitative Role Map")

        role_totals = collections.defaultdict(float)
        job_totals  = collections.defaultdict(float)

        for name in Traveler.roster:
            trav = Traveler.roster[name]
            for day in trav.roles:
                frac = 1.0 / len(trav.roles[day])
                for role in trav.roles[day]:
                    role_totals[role] += frac
            for day in trav.jobs:
                frac = 1.0 / len(trav.jobs[day])
                for job in trav.jobs[day]:
                    job_totals[job] += frac

        role_total  = sum(role_totals.values())
        job_total   = sum(job_totals.values())
        assert abs(role_total - job_total) <= 1e-6

        print >> common, "Total Role days =", role_total
        print >> common, "Total Job  days =", job_total
        print >> common


        for role in roles:
            if role_totals[role] == 0: continue
            print >> common, "\t%12s %51.1f %12s %12.3f" %\
                (role, role_totals[role], \
                "", 100.0 * role_totals[role] / role_total)

            jobs = list(cls.role_map[role])
            jobs.sort (key = lambda x: (job_totals[x], x), reverse = True)

            for index, job in enumerate(jobs, 1):
                if job_totals[job] == 0: continue
                print role, job, role_totals[role], job_totals[job]
                print >> common, "\t\t%6d. %35s %12.1f % 12.3f %12.3f" % \
                    (index, job, job_totals[job], \
                100.0 * job_totals[job] / role_totals[role],
                100.0 * job_totals[job] / role_total)
            print >> common


    print >> common, "\n", "_" * 60, "\n" #--ERROR OCCURS FOR THIS LINE ****************
    print >> common, "\nRoles in Total Tripday order\n"
    roles = role_totals.keys()
    roles.sort (order = lambda x: (role_totals[x], x), reverse = True)
    for index, role, in enumerate(roles,1):
        print >> common, "%6d. %15s %12.1f %12.3f" % \
            (index, role, role_totals[role], \
            100.0 * role_totals[role]/role_total)

    print >> common, "\n", "_" * 60, "\n"
    print >> common, "\nDetailed Trip Roles in Total Tripday order"
    jobs = job_totals.keys()
    jobs.sort (key = lambda x: (job_totals[x], x), reverse = True)
    for index, job in jobs:
        print >> common, "%6d. %35s %12.1f %12.3f" % \
            (index, job, job_totals[job], 100.0 * job_totals[job] / job_total)


    p.close()

So first things first. When you define a function, the function is not executed. Only the name is noted in the namespace. Only when the function is called (aka invoked), does it actually execute the code within the function (this is true assuming you have no syntax errors).

So the interpreter handles your imports, etc (at the top of the file) and then notices that you have a function (so it notes its name) and continues executing the rest of the code (the stuff after the function definition). It is at this point that it sees print >> common . Since common is not on the memory stack (it has never been defined before), the interpreter doesn't know what its value is and therefore raises a NameError .

Note that this will still happen when you call your function, as it also uses common before it is defined.

Hope this helps

Indentation error. The problem statement was not indented within its function, and thus appeared to be Python as a statement to be executed at class definition time.

Thanks to all who tried to help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM