# Modify 'import' command

**URL:** <https://discuss.python.org/t/modify-import-command/109468>\
**Category:** Python Help\
**Created:** [October 13, 2026, 9:10pm UTC](https://discuss.python.org/t/modify-import-command/109468 "2026-10-13T21:10:31Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![NickC](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/nickc/32/37293_2.png) [@NickC](https://discuss.python.org/u/NickC)\
**Post date:** [October 13, 2026, 9:10pm UTC](https://discuss.python.org/t/modify-import-command/109468/1 "2026-10-13T21:10:31Z")

</div>

Does anyone know if it is possible to intercept the `import` statement somehow so that the source code could be automatically modified before it is saved as a compiled .pyc file? I think some might call this monkey-patching.

I do have an example of how to do this manually using a source\_to\_code PatchedLoader but no idea how to apply that to all imports automatically.

---

<div class="post-metadata">

**Author:** ![aroberge](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/aroberge/32/6200_2.png) [@aroberge](https://discuss.python.org/u/aroberge)\
**Post date:** [October 13, 2026, 9:28pm UTC](https://discuss.python.org/t/modify-import-command/109468/2 "2026-10-13T21:28:21Z")

</div>

Yes, this is done using an import hook. There are many examples that you can find online. I wrote a library to help you do that [Ideas: making it easier to extend Python’s syntax — ideas 0.3.14 documentation](https://aroberge.github.io/ideas/docs/html/). There are others on Pypi. One that is less focused on code modification but does support all manners of patching is wrapt.

---

<div class="post-metadata">

**Author:** ![jonathandung](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/jonathandung/32/35459_2.png) [@jonathandung](https://discuss.python.org/u/jonathandung)\
**Post date:** [October 13, 2026, 11:06pm UTC](https://discuss.python.org/t/modify-import-command/109468/3 "2026-10-13T23:06:17Z")

</div>

Why would you want to do this?
