graphqlstrawberry-graphql

GraphQL Python Strawberry refactor common types


I am using Python 3.10 and Strawberry 0.139

Is there any way to refractor out like-terms to write less code for defining types?

Lets say I have two types in my schema

@strawberry.type
class Home(Address):
    name: str 
    location: str 
    description: str
    phone: int

@strawberry.type
class Business(Address):
    name: str 
    fax: int
    location: str 
    description: str
    phone: int

Is there a way I can refractor out like terms in a class using the abc library. Note that I am not referring to interfaces where you have to write in the inherited code. Something like this:

from abc import ABC

class Contact(ABC):
    location: str 
    description: str
    phone: int

@strawberry.type
class Home(Address):
    name: str 

@strawberry.type
class Business(Address):
    name: str 
    fax: int

Solution

  • Inherit from a base strawberry.type. Unlike interfaces, the base type won't be in the schema (unless explicitly included).

    @strawberry.type
    class Contact:
        location: str 
        description: str
        phone: int
    
    @strawberry.type
    class Home(Contact):
        name: str 
    
    @strawberry.type
    class Business(Contact):
        name: str 
        fax: int