Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Working with multiple code files and folders in Python

Tags:

python

import

I am new to Python and I haven't figured out a simple way of separating code in multiple code files and folders.

What I do today is: for each folder I create an __init__.py file. Sometimes it's empty. I don't know why I do it, but it seems necessary. That's the first difference from working with C#.

The second difference is that for any file to reference any another I must use an import, like from model.table import Table. And if I have multiple references I need to use multiple imports:

from model import table1,table2

and then in the rest of the code I must use table1.Table1 per example. If I don't want to, I should

from model.table1 import Table1
from model.table2 import Table2

and then I can use simply Table1

That differs too much from what I'm used to in C#, where if all files were in the same namespace, we didn't have to import. Is there a simpler way for me?

like image 366
Jader Dias Avatar asked May 15 '11 21:05

Jader Dias


1 Answers

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!

like image 196
Florian Avatar answered Oct 08 '22 01:10

Florian