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
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.
CodePudding user response:
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.