Question

I am having a problem that may be quite a basic thing, but as a Python learner I've been struggling with it for hours. The documentation has not provided me with an answer so far.

The problem is that an import statement included in a module does not seem to be executed when I import this module from a python script. What I have is as follows:

I have a file project.py (i.e. python library) that looks like this:

import datetime

class Project:
    """ This class is a container for project data """

    title        = ""
    manager      = ""
    date         = datetime.datetime.min

    def __init__( self, title="", manager="", date=datetime.datetime.min ):
    """ Init function with some defaults """

        self.title        = title
        self.manager      = manager
        self.date         = date

This library is later used in a script (file.py) that imports project, it starts like this:

import project

print datetime.datetime.min

The problem then arises when I try to execute this script with Python file.py. Python then complains with the folliwing NameError:

Traceback (most recent call last):
  File "file.py", line 3, in <module>
    print datetime.datetime.min
NameError: name 'datetime' is not defined

This actually happens also if I try to make the same statements (import and print) directly from the Python shell.

Shouldn't the datetime module be automatically imported in the precise moment that I call import project?

Thanks a lot in advance.

Was it helpful?

Solution

The datetime module is only imported into the project namespace. So you could access it as project.datetime.datetime.min, but really you should import it into your script directly.

Every symbol (name) that you create in your project.py file (like your Project class) ends up in the project namespace, which includes things you import from other modules. This isn't as inefficient as it might seem however - the actual datetime module is still only imported once, no matter how many times you do it. Every time you import it subsequent to the first one it's just importing the names into the current namespace, but not actually doing all the heavy lifting of reading and importing the module.

OTHER TIPS

Try thinking of the import statement as roughly equivalent to:

project = __import__('project')

Effectively an import statement is simply an assignment to a variable. There may be some side effects as the module is loaded, but from inside your script all you see is a simple assignment to a name.

You can pull in all the names from a module using from project import *, but don't do that because it makes your code much more brittle and harder to maintain. Instead either just import the module or exactly the names you want.

So for your code something like:

import datetime
from project import Project

is the sort of thing you should be doing.

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