Skip to content

Commit

Permalink
Add support for InitVar
Browse files Browse the repository at this point in the history
  • Loading branch information
dkraczkowski committed Aug 27, 2023
1 parent c54d234 commit d88eb55
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 2 deletions.
7 changes: 5 additions & 2 deletions chili/typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import sys
import typing
from dataclasses import MISSING, Field, is_dataclass
from dataclasses import MISSING, Field, InitVar, is_dataclass
from enum import Enum
from inspect import isclass as is_class
from typing import Any, Callable, ClassVar, Dict, List, NewType, Optional, Type, Union
Expand Down Expand Up @@ -198,8 +198,11 @@ def create_schema(cls: Type) -> TypeSchema:
for name, p_type in properties.items():
p_origin = get_origin_type(p_type)

if isinstance(p_type, InitVar):
continue

# ignore class vars as they are not object properties
if p_origin and p_origin is ClassVar:
if p_origin and p_origin in (ClassVar, InitVar):
continue

if name in attributes:
Expand Down
55 changes: 55 additions & 0 deletions tests/usecases/classvar_and_initvar_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
from dataclasses import InitVar
from typing import ClassVar

from chili import encodable, encode


def test_can_encode_and_ignore_classvar_attributes() -> None:

# given
@encodable
class Pet:
name: str
age: int
value: ClassVar[str] = "ignored"

def __init__(self, name: str, age: int):
self.name = name
self.age = age

example_obj = Pet("Bob", 11)

# when
state = encode(example_obj)

# then
assert state == {
"name": "Bob",
"age": 11,
}


def test_can_encode_and_ignore_initvar_attributes() -> None:

# given
@encodable
class Pet:
name: str
age: int
value: InitVar[str]

def __init__(self, name: str, age: int):
self.name = name
self.age = age
self.value = "ignored"

example_obj = Pet("Bob", 11)

# when
state = encode(example_obj)

# then
assert state == {
"name": "Bob",
"age": 11,
}

0 comments on commit d88eb55

Please sign in to comment.