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
0:04 three places listed in the previous lesson,
0:06 it will result in a ModuleNotFoundError.
0:10 When that happens, first thing that you should do is to check the syst.path
0:14 and see if it contains the directories that you think should be there.
0:18 If it doesn't, the best solution is to check the current structure of your project
0:22 and move files around. If you can't do this,
0:25 you can also modify the PYTHONPATH environment variable to include your directory.
0:31 And if none of those works,
0:33 you can also modify the sys.path
0:35 list directly. This is a very hacky solution,
0:39 but it's usually the fastest one,
0:41 specially if you want to add the parent directory of the current folder.
0:46 Another common problem is circular import.
0:49 It happens when two different modules try to import something from each other and Pyton gets
0:54 stuck. Let's see an example.
0:57 We start by executing a module_a
0:58 module_a import function_b,
1:02 from module_b. So, we start executing module_b.
1:05 But it turns out that module_b needs a different function from module_a,
1:10 but module_a is still not fully loaded so,
1:13 python fails to import this function_and you get an exception.
1:18 If you're using Python 3.8, you will actually see a nice error message saying that
1:23 it's probably a circular import error.
1:26 If you are using an older version of,
1:28 python, you'll get a pretty generic error message, saying import error cannot import name
1:33 function_b, to fix those circular import errors.
1:37 You need to refactor your code and make sure that different files are not trying
1:41 to import function from each other.
1:45 Typically, this can be solved by adding another file.
1:48 So, here we have the file.
1:51 It imports function_b from module_b and module_b imports function_a from module_a
1:58 and that's it. There are no more imports here.
2:01 Solving circular import errors here was easy, because we had only two files.
2:06 But usually solving circular imports in your projects is gonna be much more complicated, because it
2:11 will involve multiple files. So, they can be quite hard to fix.
2:17 We can avoid a lot of those problems by carefully structuring our projects.
2:21 Project containing of only one python file will be structured differently than a huge Web application
2:26 consisting of hundreds of files. So, let's take a look at three different sizes of a typical python project.