Modern Python Projects Transcripts
Chapter: Managing Python project
Lecture: Import errors

Login or purchase this course to watch this video and the rest of the course contents.
0:00 When you try to import the module_and Python cant find it in any of the three places listed in the previous lesson,
0:07 it will result in a ModuleNotFoundError. When that happens, first thing that you should do is to check the syst.path
0:15 and see if it contains the directories that you think should be there.
0:19 If it doesn't, the best solution is to check the current structure of your project and move files around. If you can't do this,
0:26 you can also modify the PythonPATH environment variable to include your directory. And if none of those works, you can also modify the sys.path
0:36 list directly. This is a very hacky solution, but it's usually the fastest one,
0:42 specially if you want to add the parent directory of the current folder. Another common problem is circular import.
0:50 It happens when two different modules try to import something from each other and Pyton gets stuck. Let's see an example.
0:58 We start by executing a module_a module_a import function_b, from module_b. So, we start executing module_b.
1:06 But it turns out that module_b needs a different function from module_a, but module_a is still not fully loaded so,
1:14 Python fails to import this function_and you get an exception. If you're using Python 3.8, you will actually see a nice error message saying that
1:24 it's probably a circular import error. If you are using an older version of,
1:29 Python, you'll get a pretty generic error message, saying import error cannot import name function_b, to fix those circular import errors.
1:38 You need to refactor your code and make sure that different files are not trying to import function from each other.
1:46 Typically, this can be solved by adding another file. So, here we have the main.py file.
1:52 It imports function_b from module_b and module_b imports function_a from module_a and that's it. There are no more imports here.
2:02 Solving circular import errors here was easy, because we had only two files.
2:07 But usually solving circular imports in your projects is gonna be much more complicated, because it
2:12 will involve multiple files. So, they can be quite hard to fix. We can avoid a lot of those problems by carefully structuring our projects.
2:22 Project containing of only one Python file will be structured differently than a huge Web application
2:27 consisting of hundreds of files. So, let's take a look at three different sizes of a typical Python project.


Talk Python's Mastodon Michael Kennedy's Mastodon