pythonpython-3.xpython-modulepython-packagingpython-contextvars

Using a python package in the current app and its child package


I have a FastAPI app that uses package A as a dependency. On every request to the FastAPI app, package A stores some request string in a ContextVar inside the package. The FastAPI app also uses package B. This package B uses package A as an internal dependency to get the data of the current context variable and perform some operations with it.

enter image description here

I tested this scenario, and it works fine. So my question is, how does python manage to share package A resources between the FastAPI app and package B? I mean, how does it work behind the scene?

Note: I use pip as a package manager.


Solution

  • Python subdependencies are not isolated, so when your app imports package A, and when package B does, it's the same code (usually <python location>/site_packages/package_a). So, if package A creates a global ContextVar, which is imported in both your app and package B, it will be the same object.

    This is also why you can get package version conflicts; if your app has package_a==1.0.0 in its requirements.txt file, and B has package_a>=2.0.0, then the installation will fail, because there is no version that satisfies both those requirements.