afkbowflexin
afkbowflexin

Reputation: 4089

Python name error after importing file

I'm playing with Python on my Mac, it's the default installation, version 2.7.2. For some reason, when I import a file in my current directory, it successfully imports, but when I try to call a function in the file, it gives me: NameError: name 'gcd' is not defined

This is what's inside the file (lab1.py):

def gcd(x, y):
    if x % y == 0:
        return y
    else:
        return gcd(y, x % y)

def f(x):
    return x*x

At the prompt, I just type import lab1. It imports successfully. Notably, if I'm not in the directory with lab1.py it errors out, so I know it's getting the right file. What am I missing?

Upvotes: 1

Views: 851

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1124110

You need to refer to names in the module via the global name you imported.

If you import just lab1, then refer to names in that module as attributes on the module object:

lab1.gcd(10, 3)

or you need to import names from the module:

from lab1 import gcd

to create a reference in your current module to the same function. An alternative spelling would be:

import lab1.gcd as gcd

Upvotes: 2

Related Questions