diff --git a/case-study-porting-chardet-to-python-3.html b/case-study-porting-chardet-to-python-3.html index d6f121c..e6a91d3 100755 --- a/case-study-porting-chardet-to-python-3.html +++ b/case-study-porting-chardet-to-python-3.html @@ -246,7 +246,7 @@ RefactoringTool: test.py

Translated into English, that means “import the universaldetector module; that’s in the same directory I am,” where “I” is the chardet/__init__.py file. This is called a relative import. It’s a way for the files within a multi-file module to reference each other, without worrying about naming conflicts with other modules you may have installed in your import search path. This import statement will only look for the universaldetector module within the chardet/ directory itself. -

These two concepts — __init__.py and relative imports — mean that you can break up your module into as many pieces as you like. The chardet module comprises 36 .py files — 36! Yet all you need to do to start using it is import chardet, then you can call the main chardet.detect() function. Unbeknowst to your code, the detect() function is actually defined in the chardet/__init__.py file. Also unbeknowst to you, the detect() function uses a relative import to reference a class defined in chardet/universaldetector.py, which in turn uses relative imports on five other files, all contained in the chardet/ directory. +

These two concepts — __init__.py and relative imports — mean that you can break up your module into as many pieces as you like. The chardet module comprises 36 .py files — 36! Yet all you need to do to start using it is import chardet, then you can call the main chardet.detect() function. Unbeknownst to your code, the detect() function is actually defined in the chardet/__init__.py file. Also unbeknownst to you, the detect() function uses a relative import to reference a class defined in chardet/universaldetector.py, which in turn uses relative imports on five other files, all contained in the chardet/ directory.

If you ever find yourself writing a large library in Python (or more likely, when you realize that your small library has grown into a large one), take the time to refactor it into a multi-file module. It’s one of the many things Python is good at, so take advantage of it.