Skip to content

Commit 853f5a0

Browse files
authored
feat: ✨ PYTHON_INJECTION_THREADSAFE env var
1 parent 53f7e47 commit 853f5a0

File tree

3 files changed

+322
-274
lines changed

3 files changed

+322
-274
lines changed

README.md

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -64,8 +64,14 @@ if __name__ == "__main__":
6464

6565
## Resources
6666

67-
> ⚠️ The package isn't threadsafe, for better performance in single-threaded applications and those using `asyncio`.
68-
> So remember to use `threading.Lock` if you're writing a multithreaded program.
67+
> ⚠️ The package isn't threadsafe by default, for better performance in single-threaded applications and those using
68+
> `asyncio`.
69+
>
70+
> Non-threadsafe functions are those that resolve dependencies or define scopes. They all come with an optional
71+
> parameter `threadsafe`.
72+
>
73+
> You can set `PYTHON_INJECTION_THREADSAFE=1` in environment variables to make the package fully threadsafe. The
74+
> environment variable is resolved at the **Python module level**, so be careful if the variable is defined dynamically.
6975
7076
* [**Basic usage**](https://github.com/100nm/python-injection/tree/prod/documentation/basic-usage.md)
7177
* [**Scoped dependencies**](https://github.com/100nm/python-injection/tree/prod/documentation/scoped-dependencies.md)
Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,11 @@
11
from contextlib import nullcontext
2+
from os import getenv
23
from threading import RLock
3-
from typing import Any, ContextManager
4+
from typing import Any, ContextManager, Final
5+
6+
_PYTHON_INJECTION_THREADSAFE: Final[bool] = bool(getenv("PYTHON_INJECTION_THREADSAFE"))
47

58

69
def get_lock(threadsafe: bool | None = None) -> ContextManager[Any]:
7-
return RLock() if threadsafe else nullcontext()
10+
cond = _PYTHON_INJECTION_THREADSAFE if threadsafe is None else threadsafe
11+
return RLock() if cond else nullcontext()

0 commit comments

Comments
 (0)