{"course":{"slug":"python-for-ai","title":"Python, from Zero, for AI","url":"https://addaly.com/learn/python-for-ai","level":"beginner","track":"build"},"lesson":{"slug":"modules-and-imports","title":"Modules: splitting a script across files without breaking it","url":"https://addaly.com/learn/python-for-ai/modules-and-imports","position":26,"of":89,"minutes":8,"answer":"An import executes the module once and caches it, and Python searches the script's own folder first, which is why naming a file json.py breaks the real one.","keyIdea":"An import executes the module once and caches it, and Python searches the script's own folder first, which is why naming a file `json.py` breaks the real one."},"body":{"format":"markdown","text":"## Every `.py` file is already a module\n\nPut this in `money.py`:\n\n```python\nTAX_RATE = 0.18\n\ndef with_tax(amount):\n    return round(amount * (1 + TAX_RATE), 2)\n```\n\nAnd in `main.py`, in the same folder:\n\n```python\nimport money\n\nprint(money.with_tax(100))     # 118.0\n```\n\nThat is the whole mechanism. No registration, no build step. The file name without `.py` is the module name.\n\nThree ways to bring things in:\n\n```python\nimport money                       # money.with_tax(...)\nfrom money import with_tax         # with_tax(...)\nimport money as m                  # m.with_tax(...)\n```\n\nThe first keeps the source of the name visible at every call, which is worth more than the characters it costs. The second is fine for a handful of names you use constantly. Avoid `from money import *`: it dumps every public name into your file, so nobody can tell where anything came from, and a new name in `money` can silently shadow one of yours.\n\n## What `import` actually does\n\nThe first time a module is imported, Python finds the file, **executes the whole file top to bottom**, and stores the resulting module object in `sys.modules`. Every later import of the same name finds it there and does not re-run anything.\n\nTwo consequences.\n\n**Top-level code runs on import.** If `money.py` ends with `print(with_tax(100))`, that line runs the moment anybody imports the module, including a test runner and a documentation tool. Which is why every script that is also importable ends with:\n\n```python\ndef main():\n    print(with_tax(100))\n\nif __name__ == \"__main__\":\n    main()\n```\n\n`__name__` is `\"__main__\"` when the file is the one you ran, and the module's own name when it was imported. The guard means \"only do this when I am the program, not when I am a library\".\n\n**Re-importing does not pick up edits.** In a long-running REPL or notebook, editing `money.py` and re-running `import money` changes nothing, because the module is cached. Restart the interpreter, or use `importlib.reload(money)`, which has enough caveats that restarting is usually quicker.\n\n## Where Python looks\n\n`sys.path` is the list of folders searched, in order: the folder containing the script you ran, then anything in the `PYTHONPATH` environment variable, then the installed packages of the current environment.\n\n```python\nimport sys; print(sys.path)\n```\n\nTwo failures come straight out of that list.\n\n**`ModuleNotFoundError` for your own file** usually means you ran Python from a different folder than the one the file is in. The first entry of `sys.path` is the script's folder, not your current directory, so `python3 tools/run.py` can import things next to `run.py` but not things next to you.\n\n**Your file shadows a real module.** Name a file `random.py`, `json.py`, `email.py` or `types.py` and your file wins, because the script's own folder is searched first. The error that follows is bizarre (`AttributeError: module 'random' has no attribute 'randint'`) and the fix is to rename your file and delete the `__pycache__` folder that still holds the compiled shadow.\n\n## Circular imports\n\n`a.py` imports `b`, and `b.py` imports `a`. The second import finds a half-executed module and fails with `ImportError: cannot import name 'x' from partially initialized module`.\n\nThis is a design signal, not a puzzle to solve. Either the two modules are one, or a third module holds what they share. Moving the import inside the function that needs it defers the problem and works, and it is a patch rather than a fix.\n\n## Two commands that end most import arguments\n\n```python\nimport money\nprint(money.__file__)      # exactly which file got loaded\nprint(dir(money))          # every name the module defines\n```\n\n`__file__` settles \"which version am I running\" in one line: the answer is frequently a copy in a different folder, or a package installed in another environment. `dir()` shows what is actually available, which beats guessing at a name from a tutorial written for an older release.\n\n## The standard library is large and already installed\n\nBefore adding a dependency, check whether Python ships it: `json`, `csv`, `pathlib`, `datetime`, `re`, `math`, `random`, `collections`, `itertools`, `statistics`, `sqlite3`, `urllib`, `unittest`, `logging`, `argparse`, `subprocess`, `zipfile`, `hashlib`, `secrets`. A working SQL database, a JSON parser and a web client all come free with the interpreter.\n\nEvery dependency you do not add is one you never have to upgrade, audit or explain.\n\n## Try this now\n\nSplit any script you have written into two files: one with the functions, one that imports them and runs. Add the `__name__` guard to both. Then rename the function file to `json.py` and run it, so you see the shadowing failure once, on purpose, when it is harmless."},"check":{"question":"A colleague adds `analysis.py` to a project folder and the previously working `import numpy` in another file starts failing with an AttributeError deep inside numpy. They swear they changed nothing else. What is the first thing to check?","options":[{"text":"Whether numpy was upgraded, since AttributeError inside a library almost always means a version change.","correct":false,"tempting":"A reasonable general instinct, but it ignores the one change that was actually made and the folder-first search order."},{"text":"Whether the virtual environment is activated, since an unactivated environment resolves imports against the system Python.","correct":false,"tempting":"Names a real cause of import trouble, though that produces ModuleNotFoundError rather than an attribute failure inside the library."},{"text":"Whether any file in that folder (or a stale `__pycache__` entry) shares a name with a module numpy imports, since the script's folder is searched before installed packages.","correct":true},{"text":"Whether the new file has a circular import back to the caller, which leaves numpy partially initialised.","correct":false,"tempting":"Circular imports do produce partially initialised modules, but only between the two files involved, not for an unrelated installed package."}]},"prev":{"slug":"docstrings-and-type-hints","title":"Saying what a function expects, and what checks it","url":"https://addaly.com/learn/python-for-ai/docstrings-and-type-hints"},"next":{"slug":"project-layout","title":"Laying out a project so the imports keep working","url":"https://addaly.com/learn/python-for-ai/project-layout"},"authorship":"Founder and series editor: Dr Mustafa Mun. Written by AI models to a written standard. Source and assessment review continues. Academic review invited.","review":{"status":"Draft, open for academic review"},"cite":"Addaly (2026) 'Modules: splitting a script across files without breaking it', in Python, from Zero, for AI. Edited by M. Mun. Addaly. Available at: https://addaly.com/learn/python-for-ai/modules-and-imports (Accessed: 29 November 2026).","licence":{"name":"CC BY-NC-SA 4.0","url":"https://creativecommons.org/licenses/by-nc-sa/4.0/"},"reader":{"schema":1,"title":"Modules: splitting a script across files without breaking it","courseTitle":"Python, from Zero, for AI","module":{"index":3,"slug":"functions-and-structure","title":"Functions, modules, and code you can read again in March"},"answer":null,"keyIdea":"An import executes the module once and caches it, and Python searches the script’s own folder first, which is why naming a file `json.py` breaks the real one.","hero":{"kind":"plate","image":null,"alt":null,"caption":null},"blocks":[{"t":"h2","id":"every-py-file-is-already-a-module","runs":[{"text":"Every "},{"text":".py","code":true},{"text":" file is already a module"}]},{"t":"p","runs":[{"text":"Put this in "},{"text":"money.py","code":true},{"text":":"}]},{"t":"code","lang":"python","label":"Python","text":"TAX_RATE = 0.18\n\ndef with_tax(amount):\n    return round(amount * (1 + TAX_RATE), 2)"},{"t":"p","runs":[{"text":"And in "},{"text":"main.py","code":true},{"text":", in the same folder:"}]},{"t":"code","lang":"python","label":"Python","text":"import money\n\nprint(money.with_tax(100))     # 118.0"},{"t":"p","runs":[{"text":"That is the whole mechanism. No registration, no build step. The file name without "},{"text":".py","code":true},{"text":" is the module name."}]},{"t":"p","runs":[{"text":"Three ways to bring things in:"}]},{"t":"code","lang":"python","label":"Python","text":"import money                       # money.with_tax(...)\nfrom money import with_tax         # with_tax(...)\nimport money as m                  # m.with_tax(...)"},{"t":"p","runs":[{"text":"The first keeps the source of the name visible at every call, which is worth more than the characters it costs. The second is fine for a handful of names you use constantly. Avoid "},{"text":"from money import *","code":true},{"text":": it dumps every public name into your file, so nobody can tell where anything came from, and a new name in "},{"text":"money","code":true},{"text":" can silently shadow one of yours."}]},{"t":"h2","id":"what-import-actually-does","runs":[{"text":"What "},{"text":"import","code":true},{"text":" actually does"}]},{"t":"p","runs":[{"text":"The first time a module is imported, Python finds the file, "},{"text":"executes the whole file top to bottom","b":true},{"text":", and stores the resulting module object in "},{"text":"sys.modules","code":true},{"text":". Every later import of the same name finds it there and does not re-run anything."}]},{"t":"p","runs":[{"text":"Two consequences."}]},{"t":"p","runs":[{"text":"Top-level code runs on import.","b":true},{"text":" If "},{"text":"money.py","code":true},{"text":" ends with "},{"text":"print(with_tax(100))","code":true},{"text":", that line runs the moment anybody imports the module, including a test runner and a documentation tool. Which is why every script that is also importable ends with:"}]},{"t":"code","lang":"python","label":"Python","text":"def main():\n    print(with_tax(100))\n\nif __name__ == \"__main__\":\n    main()"},{"t":"p","runs":[{"text":"__name__","code":true},{"text":" is "},{"text":"\"__main__\"","code":true},{"text":" when the file is the one you ran, and the module’s own name when it was imported. The guard means “only do this when I am the program, not when I am a library”."}]},{"t":"p","runs":[{"text":"Re-importing does not pick up edits.","b":true},{"text":" In a long-running REPL or notebook, editing "},{"text":"money.py","code":true},{"text":" and re-running "},{"text":"import money","code":true},{"text":" changes nothing, because the module is cached. Restart the interpreter, or use "},{"text":"importlib.reload(money)","code":true},{"text":", which has enough caveats that restarting is usually quicker."}]},{"t":"h2","id":"where-python-looks","runs":[{"text":"Where Python looks"}]},{"t":"p","runs":[{"text":"sys.path","code":true},{"text":" is the list of folders searched, in order: the folder containing the script you ran, then anything in the "},{"text":"PYTHONPATH","code":true},{"text":" environment variable, then the installed packages of the current environment."}]},{"t":"code","lang":"python","label":"Python","text":"import sys; print(sys.path)"},{"t":"p","runs":[{"text":"Two failures come straight out of that list."}]},{"t":"p","runs":[{"text":"ModuleNotFoundError","b":true,"code":true},{"text":" for your own file","b":true},{"text":" usually means you ran Python from a different folder than the one the file is in. The first entry of "},{"text":"sys.path","code":true},{"text":" is the script’s folder, not your current directory, so "},{"text":"python3 tools/run.py","code":true},{"text":" can import things next to "},{"text":"run.py","code":true},{"text":" but not things next to you."}]},{"t":"p","runs":[{"text":"Your file shadows a real module.","b":true},{"text":" Name a file "},{"text":"random.py","code":true},{"text":", "},{"text":"json.py","code":true},{"text":", "},{"text":"email.py","code":true},{"text":" or "},{"text":"types.py","code":true},{"text":" and your file wins, because the script’s own folder is searched first. The error that follows is bizarre ("},{"text":"AttributeError: module 'random' has no attribute 'randint'","code":true},{"text":") and the fix is to rename your file and delete the "},{"text":"__pycache__","code":true},{"text":" folder that still holds the compiled shadow."}]},{"t":"h2","id":"circular-imports","runs":[{"text":"Circular imports"}]},{"t":"p","runs":[{"text":"a.py","code":true},{"text":" imports "},{"text":"b","code":true},{"text":", and "},{"text":"b.py","code":true},{"text":" imports "},{"text":"a","code":true},{"text":". The second import finds a half-executed module and fails with "},{"text":"ImportError: cannot import name 'x' from partially initialized module","code":true},{"text":"."}]},{"t":"p","runs":[{"text":"This is a design signal, not a puzzle to solve. Either the two modules are one, or a third module holds what they share. Moving the import inside the function that needs it defers the problem and works, and it is a patch rather than a fix."}]},{"t":"h2","id":"two-commands-that-end-most-import-arguments","runs":[{"text":"Two commands that end most import arguments"}]},{"t":"code","lang":"python","label":"Python","text":"import money\nprint(money.__file__)      # exactly which file got loaded\nprint(dir(money))          # every name the module defines"},{"t":"p","runs":[{"text":"__file__","code":true},{"text":" settles “which version am I running” in one line: the answer is frequently a copy in a different folder, or a package installed in another environment. "},{"text":"dir()","code":true},{"text":" shows what is actually available, which beats guessing at a name from a tutorial written for an older release."}]},{"t":"h2","id":"the-standard-library-is-large-and-already-installed","runs":[{"text":"The standard library is large and already installed"}]},{"t":"p","runs":[{"text":"Before adding a dependency, check whether Python ships it: "},{"text":"json","code":true},{"text":", "},{"text":"csv","code":true},{"text":", "},{"text":"pathlib","code":true},{"text":", "},{"text":"datetime","code":true},{"text":", "},{"text":"re","code":true},{"text":", "},{"text":"math","code":true},{"text":", "},{"text":"random","code":true},{"text":", "},{"text":"collections","code":true},{"text":", "},{"text":"itertools","code":true},{"text":", "},{"text":"statistics","code":true},{"text":", "},{"text":"sqlite3","code":true},{"text":", "},{"text":"urllib","code":true},{"text":", "},{"text":"unittest","code":true},{"text":", "},{"text":"logging","code":true},{"text":", "},{"text":"argparse","code":true},{"text":", "},{"text":"subprocess","code":true},{"text":", "},{"text":"zipfile","code":true},{"text":", "},{"text":"hashlib","code":true},{"text":", "},{"text":"secrets","code":true},{"text":". A working SQL database, a JSON parser and a web client all come free with the interpreter."}]},{"t":"p","runs":[{"text":"Every dependency you do not add is one you never have to upgrade, audit or explain."}]},{"t":"h2","id":"try-this-now","runs":[{"text":"Try this now"}],"role":"try"},{"t":"p","runs":[{"text":"Split any script you have written into two files: one with the functions, one that imports them and runs. Add the "},{"text":"__name__","code":true},{"text":" guard to both. Then rename the function file to "},{"text":"json.py","code":true},{"text":" and run it, so you see the shadowing failure once, on purpose, when it is harmless."}]}],"check":{"question":[{"text":"A colleague adds "},{"text":"analysis.py","code":true},{"text":" to a project folder and the previously working "},{"text":"import numpy","code":true},{"text":" in another file starts failing with an AttributeError deep inside numpy. They swear they changed nothing else. What is the first thing to check?"}],"options":[{"text":[{"text":"Whether numpy was upgraded, since AttributeError inside a library almost always means a version change."}],"correct":false,"tempting":[{"text":"A reasonable general instinct, but it ignores the one change that was actually made and the folder-first search order."}]},{"text":[{"text":"Whether the virtual environment is activated, since an unactivated environment resolves imports against the system Python."}],"correct":false,"tempting":[{"text":"Names a real cause of import trouble, though that produces ModuleNotFoundError rather than an attribute failure inside the library."}]},{"text":[{"text":"Whether any file in that folder (or a stale "},{"text":"__pycache__","code":true},{"text":" entry) shares a name with a module numpy imports, since the script’s folder is searched before installed packages."}],"correct":true,"tempting":null},{"text":[{"text":"Whether the new file has a circular import back to the caller, which leaves numpy partially initialised."}],"correct":false,"tempting":[{"text":"Circular imports do produce partially initialised modules, but only between the two files involved, not for an unrelated installed package."}]}],"order":[3,2,1,0],"why":null},"prev":{"slug":"docstrings-and-type-hints","title":"Saying what a function expects, and what checks it","minutes":8},"next":{"slug":"project-layout","title":"Laying out a project so the imports keep working","minutes":8}}}