Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,8 +64,14 @@ if __name__ == "__main__":

## Resources

> ⚠️ The package isn't threadsafe, for better performance in single-threaded applications and those using `asyncio`.
> So remember to use `threading.Lock` if you're writing a multithreaded program.
> ⚠️ The package isn't threadsafe by default, for better performance in single-threaded applications and those using
> `asyncio`.
>
> Non-threadsafe functions are those that resolve dependencies or define scopes. They all come with an optional
> parameter `threadsafe`.
>
> You can set `PYTHON_INJECTION_THREADSAFE=1` in environment variables to make the package fully threadsafe. The
> environment variable is resolved at the **Python module level**, so be careful if the variable is defined dynamically.

* [**Basic usage**](https://github.com/100nm/python-injection/tree/prod/documentation/basic-usage.md)
* [**Scoped dependencies**](https://github.com/100nm/python-injection/tree/prod/documentation/scoped-dependencies.md)
Expand Down
8 changes: 6 additions & 2 deletions injection/_core/common/threading.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
from contextlib import nullcontext
from os import getenv
from threading import RLock
from typing import Any, ContextManager
from typing import Any, ContextManager, Final

_PYTHON_INJECTION_THREADSAFE: Final[bool] = bool(getenv("PYTHON_INJECTION_THREADSAFE"))


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