python-injector / python-injector/injector

`injector.Injector.create_object` on pydantic-settings `BaseSettings` does not without factory function in Injector

Open
#253 4 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Python
Stars
1.5k
Forks
94
PR merge metrics
No merged PRs in 30d

Description

As stated in this closed bug at pydantic-settings, i cannot achieve an initialization through injector on python 3.8 and 3.9 (works ok on 3.10+) without a factory method.

The issue was turned down by the pydantic-settings team.

The error message

TypeError: unsupported operand type(s) for |: 'type' and 'NoneType'

Why ?

Pydantic BaseSettings base class uses PEP-604 (str | None) annotation instead of PEP-484 (Union, Optional).
It seems that Pydantic BaseSettings class don’t like to be initialized through cls.__new__(cls).

This works

class Configuration(Module):
    def configure(self, binder: Binder):
        binder.bind(BaseSettings, scope=SingletonScope, to=lambda: BaseSettings())

This does not

class Configuration(Module):
    def configure(self, binder: Binder):
        binder.bind(BaseSettings, scope=SingletonScope)

Reproduced issue

https://github.com/Guibod/pydantic-settings-bug-298

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start at injector.Injector.create_object and reproduce the reported binding behavior with pydantic-settings BaseSettings on Python 3.8 and 3.9, using the linked pydantic-settings-bug-298 reproduction. Done means a direct BaseSettings binding works without requiring a factory function, while preserving the behavior that works on Python 3.10+.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
backend
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.