0

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.

Amr Saeed
  • 177
  • 2
  • 12

1 Answers1

1

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.

M.O.
  • 1,712
  • 1
  • 6
  • 18
  • 1
    Thanks for your answer. If I understand you correctly, no matter how many times a package is mentioned for installation inside the app or its dependencies, it will always be translated to a single package with a single version. Also, the import of its modules anywhere will reference the same object. Also, can you give me a reference that can help me read more about this if you have one? – Amr Saeed Oct 01 '22 at 11:29
  • Yes, that is correct. A good place to start would probably be pip's own [documentation about dependency resolution](https://pip.pypa.io/en/stable/topics/dependency-resolution/). – M.O. Oct 01 '22 at 11:37
  • One last thing that came to my mind, using `import pkg` vs `import pkg as p` won't make a difference. Python is smart enough to recognize it's the same object. Right? – Amr Saeed Oct 01 '22 at 11:44
  • 1
    You're right, that won't make a difference. – M.O. Oct 01 '22 at 12:00