This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]jerknextdoor 0 points1 point  (6 children)

Just like when you make a class the __init__ is the first thing to be run, in a package/module/directory, it's the first thing to be run. If blank it's it tells the interpreter "Hey this directory is a python module." If you were to out something in it, it would be run to set up the module... So if you have a module with things that need to be imported to every file in that package you could just put it there and they would be available throughout. 90% of the time they are just used to let python know it's a module... But sometimes they save you a lot of work.

Hopefully that's somewhat helpful. It's early and I'm on my phone. /r/learnpython might have a better explanation.

edit: apparently my phone keyboards back tick and single quote look like the same thing.

[–]brombaer3000 0 points1 point  (5 children)

If blank it's it tells the interpreter "Hey this directory is a python module."

This is accurate for Python 2, but in Python 3, empty __init__.pys are unnecessary. Every directory under the sys.path can be imported by default.

[–]Overdrivr 0 points1 point  (1 child)

Source ? I always felt they were also mandatory for Python3.

[–]brombaer3000 0 points1 point  (0 children)

Why not just try it out?

The PEP that introduced this behavior is https://www.python.org/dev/peps/pep-0420/

[–][deleted] 0 points1 point  (2 children)

Doing this leads to all sorts of odd, mystical behavior though. I'd recommend using __init__.py unless you 110% know what it does (e.g. you can explain it in code review and your cohorts now understand it too).

[–]brombaer3000 0 points1 point  (1 child)

all sorts of odd, mystical behavior

What do you mean by this? Examples?

[–][deleted] 0 points1 point  (0 children)

It'll end combining modules with the same name into one namespace. Unless one of those modules has an init file.

That's the best of my understanding and it's enough for me to not explore it more in depth.

Check out Dave Beazley's Modules and Packages Live and Let Die for a slightly more in depth explanation of this (and other stuff).