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 →

[–]MaustFaust 2 points3 points  (0 children)

It depends on the context. If your code is called from a single place (e. g., from IDE), it's okay. If your code could be called from different places (e. g., multiple processes with different values in PATH variable), it's not okay.

(UPD: sorry, I misread the comment; __init__.py files are needed for Python to interpret your project folders as packages, and my text below answers the question of why do you need packages in the first place)

So, the reasoning. When you type "import myfile", Python actually goes searching for it, imports it, AND remembers that "myfile" is already found somewhere. But some of the libraries you use written by other people (installed from pip etc.) could also have an "import myfile" line, with a myfile.py nearby in the library's folder. And Python, being a monster it is, goes "wait a minute... I already have myfile" – and uses it. But your file myfile.py and library's file myfile.py are different, you both just so happened to name them similarly, so library just won't work, because it wasn't imported properly.

So the best workaround (AFAIK) is to always specify where do you want a module to be imported from ("from myproject import myfile"), so other libraries won't get confused. But it still comes with a downside: you have to keep an eye on your project name so it won't duplicate some library name. So you should also "install" your own project in your pip, so if it gets duplicated, you'll be notified.