Working with multiple code files and folders in Python

You should read up on modules: http://docs.python.org/tutorial/modules.html

Basically, I think you aren't organizing your code right. With Python, directories and files have a meaning; it's not just what you write into the files. With every new directory (with __init__.py) and every new file you create a new "namespace"...

If you have the file /mydatabase/model.py and the Table1, Table2, etc defined in that model.py file you can simply:

from mydatabase.model import *

Do not create a new file for each Table class!


The python import system is fairly similar to C#'s namespaces from what I understand of it. You can customize import behavior of modules in __init__.py if you really want to. You can also use import * or from x import * to pull all public objects defined by a module into your current namespace.

Consider in C#:

using System;
Console.WriteLine("hello world!");

In python, you could do (using this completely contrived situation):

system/
system/__init__.py
system/console.py

In __init__.py:

import console

In system/console.py:

import sys

def write_line(s):
    sys.stdout.write(s)

Now in your python code you could do:

from system import *
console.write_line('hello world!')

This is not generally considered a good idea in Python, however. For a bit more detail and good recommendations, check out this article: http://effbot.org/zone/import-confusion.htm

Tags:

Python

Import