question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

[QUESTION] dependencies inherited from typing.Generic

See original GitHub issue

How can I avoid ‘args’ and ‘kwargs’ as a required query parameters if I use typing.Generic?

I have got next generic base class

from typing import Generic, Type, TypeVar

ModelType = TypeVar("ModelType", bound=BaseModel)
CreateSchemaType = TypeVar("CreateSchemaType", bound=BaseModel)
UpdateSchemaType = TypeVar("UpdateSchemaType", bound=BaseModel)

class CRUDBase(Generic[ModelType, CreateSchemaType, UpdateSchemaType]):

    def __init__(self, db: Database, table: Table, model: Type[ModelType]):
        self.db = db
        self.model = model
        self.table = table

And successor class which used as a dependency


class UserService(CRUDBase[User, UserCreate, UserUpdate]):
    def __init__(self, db: Database = Depends(get_db)):
        super().__init__(db, UserTable, User)

Since typing.Generic has overwritten __new__ method, so FastAPI makes args and kwargs as a required query attributes.

I have only one solution with a factory function, have you another solution?

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:5 (2 by maintainers)

github_iconTop GitHub Comments

1reaction
dardosordicommented, Jun 3, 2021

Got it working somehow with this decorator.

def restore_signature(cls):
    @functools.wraps(cls)
    def wrap(*args, **kwargs):
        return cls(*args, **kwargs)

    sig = inspect.signature(cls.__init__)
    parameters = list(sig.parameters.values())[1:]

    wrap.__signature__ = sig.replace(parameters=parameters)
    return wrap
0reactions
dardosordicommented, Aug 9, 2021

@dardosordi Could you please share detail how you get it working?

class BaseService(Generic[ModelType, CreateSchemaType, UpdateSchemaType]):
    def __init__(self, model: Type[ModelType], db: Session):
      """Base class for generic service"""

@generic_dependency
class UserService(BaseService[User, UserCreate, UserUpdate]):
    def __init__(self, db: Session = Depends(get_db)):
        super().__init__(User, db)

@router.post("/signup")
def signup(user_service: UserService = Depends()):
 
Read more comments on GitHub >

github_iconTop Results From Across the Web

Dependency Injection with inheritance and Generics in .NET ...
Here's the way to register generic dependencies. public static void Main() { var services = new ServiceCollection(); services.
Read more >
Inherit a class that inherits a generic class to make it easier to ...
I'm creating a simple Dependency Injection library for Unity (no constructors available) and I want to use a generic class that implements a ......
Read more >
Crossing the Generics Divide - Jimmy Bogard
Our problem here is we need to "know" the service type at compile time in order to pass that value through to the...
Read more >
Issue 38459: typing: Classes that inherit `Generic[...]` indirectly ...
typing : Classes that inherit `Generic[...]` indirectly aren't considered generic. Type: behavior, Stage: resolved. Components: Library (Lib) ...
Read more >
Java Generics Example Tutorial - Generic Method, Class ...
Notice that at the time of list creation, we have specified that the type of elements in the list will be String. So...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found