Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File/module structure in Python

So I'm just getting started with Python, and currently working my way through http://diveintopython3.ep.io/. The code examples are nice, but the vast majority of them are little four-line snippets, and I want to see a little more of the big picture.

As I understand it--and correct me if I'm wrong--each '.py' file becomes a "module", and a group of modules in a directory becomes a "package" (at least, it does if I create a __init__.py file in that directory). What is it if I don't have a __init__.py file?

So what does each "module" file look like? Do I generally define only one class in the file? Does anything else go in that file besides the class definition and maybe a handful of import commands?

like image 813
keithjgrant Avatar asked Nov 19 '25 22:11

keithjgrant


2 Answers

What is it if I don't have a __init__.py file?

It's just a folder.

Do I generally define only one class in the file?

It depends. Not necessarily.

Does anything else go in that file besides the class definition and maybe a handful of import commands?

You can put anything you want. Anything that's valid python at least.

like image 100
Falmarri Avatar answered Nov 21 '25 14:11

Falmarri


Not really an answer, but it is always worth looking at the standard library to see how they use __init__.py in packages like sqlite3 vs. modules like SimpleHTTPServer

like image 25
Andrew Cox Avatar answered Nov 21 '25 12:11

Andrew Cox



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!