Python dataclasses.is_dataclass() Examples

The following are 30 code examples of dataclasses.is_dataclass(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module dataclasses , or try the search function .
Example #1
Source File: response.py    From selene-backend with GNU Affero General Public License v3.0 6 votes vote down vote up
def coerce_response(response_data):
    """Coerce response data to JSON serializable object with camelCase keys

    Recursively walk through the response object in case there are things
    like nested dataclasses that need to be reformatted

    :param response_data: data returned from the API request
    :returns: the same data but with keys in camelCase
    """
    if is_dataclass(response_data):
        coerced = {
            snake_to_camel(key): coerce_response(value)
            for key, value in asdict(response_data).items()
        }
    elif isinstance(response_data, dict):
        coerced = {
            snake_to_camel(key): coerce_response(value)
            for key, value in response_data.items()
        }
    elif isinstance(response_data, list):
        coerced = [coerce_response(item) for item in response_data]
    else:
        coerced = response_data

    return coerced 
Example #2
Source File: json.py    From pydantic with MIT License 6 votes vote down vote up
def pydantic_encoder(obj: Any) -> Any:
    from dataclasses import asdict, is_dataclass
    from .main import BaseModel

    if isinstance(obj, BaseModel):
        return obj.dict()
    elif is_dataclass(obj):
        return asdict(obj)

    # Check the class type and its superclasses for a matching encoder
    for base in obj.__class__.__mro__[:-1]:
        try:
            encoder = ENCODERS_BY_TYPE[base]
        except KeyError:
            continue
        return encoder(obj)
    else:  # We have exited the for loop without finding a suitable encoder
        raise TypeError(f"Object of type '{obj.__class__.__name__}' is not JSON serializable") 
Example #3
Source File: finite_diff.py    From myia with MIT License 6 votes vote down vote up
def gen_variants(self, obj: object, gen, path):
    if is_dataclass(obj):
        fields = list(obj.__dataclass_fields__.keys())
        for field in fields:
            x = getattr(obj, field)
            for variants, p in self(x, gen, path + (field,)):
                new_variants = []
                for variant in variants:
                    d = {
                        f2: (variant if f2 == field else getattr(obj, f2))
                        for f2 in fields
                    }
                    new_variants.append(type(obj)(**d))
                yield (new_variants, p)
    else:
        yield (gen(obj), path) 
Example #4
Source File: data.py    From dffml with MIT License 6 votes vote down vote up
def export_value(obj, key, value):
    # export and _asdict are not classmethods
    if hasattr(value, "ENTRY_POINT_ORIG_LABEL") and hasattr(value, "config"):
        obj[key] = {"plugin": value.ENTRY_POINT_ORIG_LABEL}
        export_value(obj[key], "config", value.config)
    elif inspect.isclass(value):
        obj[key] = value.__qualname__
    elif isinstance(value, (pathlib.Path, uuid.UUID)):
        obj[key] = str(value)
    elif hasattr(value, "export"):
        obj[key] = value.export()
    elif hasattr(value, "_asdict"):
        obj[key] = value._asdict()
    elif getattr(type(value), "__module__", None) == "numpy" and isinstance(
        getattr(value, "flatten", None), collections.Callable
    ):
        obj[key] = tuple(value.flatten())
    elif dataclasses.is_dataclass(value):
        obj[key] = export_dict(**dataclasses.asdict(value))
    elif getattr(value, "__module__", None) == "typing":
        obj[key] = STANDARD_TYPES.get(
            str(value).replace("typing.", ""), "generic"
        ) 
Example #5
Source File: typed_json_dataclass.py    From typed-json-dataclass with MIT License 6 votes vote down vote up
def _contains_non_default_init_vars(cls, previous_classes=None):
        """Check whether this dataclass contains non-default init-only vars.

        Performs a recursive check through all fields that are declared as
        dataclasses to ensure that no nested dataclasses contain init-only
        variables. The ``previous_classes`` argument is a set of previously
        checked classes to prevent infinite recursion on recursive structures.

        :param previous_classes: The set of previously checked classes.
        """
        try:
            previous_classes.add(cls)
        except AttributeError:  # NoneType
            previous_classes = {cls}

        # The identify check (.. is MISSING) is fine, MISSING is a singleton
        has_init_vars = any(field.type == InitVar and field.default is MISSING
                            for field in cls.__dataclass_fields__.values())
        children_have_init_vars = any(
                child.type._contains_non_default_init_vars(previous_classes)
                for child in fields(cls)
                if (is_dataclass(child.type)
                    and child.type not in previous_classes))
        return has_init_vars or children_have_init_vars 
Example #6
Source File: mm.py    From dataclasses-json with MIT License 6 votes vote down vote up
def _deserialize(self, value, attr, data, **kwargs):
        tmp_value = deepcopy(value)
        if isinstance(tmp_value, dict) and '__type' in tmp_value:
            dc_name = tmp_value['__type']
            for type_, schema_ in self.desc.items():
                if is_dataclass(type_) and type_.__name__ == dc_name:
                    del tmp_value['__type']
                    return schema_._deserialize(tmp_value, attr, data, **kwargs)
        for type_, schema_ in self.desc.items():
            if isinstance(tmp_value, _get_type_origin(type_)):
                return schema_._deserialize(tmp_value, attr, data, **kwargs)
        else:
            warnings.warn(
                f'The type "{type(tmp_value).__name__}" (value: "{tmp_value}") '
                f'is not in the list of possible types of typing.Union '
                f'(dataclass: {self.cls.__name__}, field: {self.field.name}). '
                f'Value cannot be deserialized properly.')
        return super()._deserialize(tmp_value, attr, data, **kwargs) 
Example #7
Source File: mm.py    From dataclasses-json with MIT License 6 votes vote down vote up
def _serialize(self, value, attr, obj, **kwargs):
        if self.allow_none and value is None:
            return None
        for type_, schema_ in self.desc.items():
            if _issubclass_safe(type(value), type_):
                if is_dataclass(value):
                    res = schema_._serialize(value, attr, obj, **kwargs)
                    res['__type'] = str(type_.__name__)
                    return res
                break
            elif isinstance(value, _get_type_origin(type_)):
                return schema_._serialize(value, attr, obj, **kwargs)
        else:
            warnings.warn(
                f'The type "{type(value).__name__}" (value: "{value}") '
                f'is not in the list of possible types of typing.Union '
                f'(dataclass: {self.cls.__name__}, field: {self.field.name}). '
                f'Value cannot be serialized properly.')
        return super()._serialize(value, attr, obj, **kwargs) 
Example #8
Source File: util.py    From ib_insync with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def df(objs, labels=None):
    """
    Create pandas DataFrame from the sequence of same-type objects.
    When a list of labels is given then only retain those labels and
    drop the rest.
    """
    import pandas as pd
    from .objects import DynamicObject
    if objs:
        objs = list(objs)
        obj = objs[0]
        if is_dataclass(obj):
            df = pd.DataFrame.from_records(dataclassAsTuple(o) for o in objs)
            df.columns = [field.name for field in fields(obj)]
        elif isinstance(obj, DynamicObject):
            df = pd.DataFrame.from_records(o.__dict__ for o in objs)
        else:
            df = pd.DataFrame.from_records(objs)
        if isinstance(obj, tuple) and hasattr(obj, '_fields'):
            # assume it's a namedtuple
            df.columns = obj.__class__._fields
    else:
        df = None
    if labels:
        exclude = [label for label in df if label not in labels]
        df = df.drop(exclude, axis=1)
    return df 
Example #9
Source File: helpers.py    From pampy with MIT License 5 votes vote down vote up
def is_dataclass(value):
    """
    Dataclass support is only enabled in Python 3.7+, or in 3.6 with the `dataclasses` backport installed
    """
    try:
        from dataclasses import is_dataclass
        return is_dataclass(value)
    except ImportError:
        return False 
Example #10
Source File: data_generation.py    From tf-quant-finance with Apache License 2.0 5 votes vote down vote up
def write_local(local_file_path: str, data_class: object) -> None:
  """Writes a dataclass object to file."""
  if not dataclasses.is_dataclass(data_class):
    raise ValueError('Object to write must be a dataclass')
  data = dataclasses.asdict(data_class)
  with tff.experimental.io.ArrayDictWriter(local_file_path) as writer:
    writer.write(data) 
Example #11
Source File: _unpack.py    From undictify with MIT License 5 votes vote down vote up
def _is_dataclass(value: TypeT) -> bool:
    """Return True if the value is a dataclass"""
    if VER_3_7_AND_UP:
        return is_dataclass(value)
    return False 
Example #12
Source File: messages.py    From ocpp with MIT License 5 votes vote down vote up
def __init__(self, unique_id, action, payload):
        self.unique_id = unique_id
        self.action = action
        self.payload = payload

        if is_dataclass(payload):
            self.payload = asdict(payload) 
Example #13
Source File: core.py    From dacite with MIT License 5 votes vote down vote up
def _build_value(type_: Type, data: Any, config: Config) -> Any:
    if is_union(type_):
        return _build_value_for_union(union=type_, data=data, config=config)
    elif is_generic_collection(type_) and is_instance(data, extract_origin_collection(type_)):
        return _build_value_for_collection(collection=type_, data=data, config=config)
    elif is_dataclass(type_) and is_instance(data, Data):
        return from_dict(data_class=type_, data=data, config=config)
    return data 
Example #14
Source File: json_serialize.py    From ReAgent with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def object_to_json(o: Any) -> str:
    assert is_dataclass(o), "Only dataclasses can be serialized"
    return json.dumps(prepare_for_json(o)) 
Example #15
Source File: json_serialize.py    From ReAgent with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def prepare_for_json(o: Any) -> Any:
    if isinstance(o, NamedTuple):
        d = {}
        for field_name in o._fields:
            d[field_name] = prepare_for_json(getattr(o, field_name))
        return d
    elif is_dataclass(o):
        return asdict(o)
    else:
        return o 
Example #16
Source File: json_serialize.py    From ReAgent with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def json_to_object(j: str, to_type: Type) -> Any:
    assert is_dataclass(to_type), "Only dataclasses can be deserialized"
    j_obj = json.loads(j)
    return from_json(j_obj, to_type) 
Example #17
Source File: _error_reporting.py    From pyquil with Apache License 2.0 5 votes vote down vote up
def json_serialization_helper(o: object) -> Any:
    if is_dataclass(o):
        return asdict(o)
    elif isinstance(o, datetime):
        return o.isoformat()
    elif isinstance(o, Exception):
        return repr(o)
    else:
        raise TypeError("unable to serialize object {}".format(o)) 
Example #18
Source File: util.py    From ib_insync with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def dataclassAsDict(obj) -> dict:
    """
    Return dataclass values as ``dict``.
    This is a non-recursive variant of ``dataclasses.asdict``.
    """
    if not is_dataclass(obj):
        raise TypeError(f'Object {obj} is not a dataclass')
    return {field.name: getattr(obj, field.name) for field in fields(obj)} 
Example #19
Source File: util.py    From ib_insync with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def dataclassAsTuple(obj) -> tuple:
    """
    Return dataclass values as ``tuple``.
    This is a non-recursive variant of ``dataclasses.astuple``.
    """
    if not is_dataclass(obj):
        raise TypeError(f'Object {obj} is not a dataclass')
    return tuple(getattr(obj, field.name) for field in fields(obj)) 
Example #20
Source File: util.py    From ib_insync with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def dataclassNonDefaults(obj) -> dict:
    """
    For a ``dataclass`` instance get the fields that are different from the
    default values and return as ``dict``.
    """
    if not is_dataclass(obj):
        raise TypeError(f'Object {obj} is not a dataclass')
    values = [getattr(obj, field.name) for field in fields(obj)]
    return {
        field.name: value for field, value in zip(fields(obj), values)
        if value != field.default and value == value and value != []} 
Example #21
Source File: util.py    From ib_insync with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def dataclassUpdate(obj, *srcObjs, **kwargs) -> object:
    """
    Update fields of the given ``dataclass`` object from zero or more
    ``dataclass`` source objects and/or from keyword arguments.
    """
    if not is_dataclass(obj):
        raise TypeError(f'Object {obj} is not a dataclass')
    for srcObj in srcObjs:
        obj.__dict__.update(dataclassAsDict(srcObj))
    obj.__dict__.update(**kwargs)
    return obj 
Example #22
Source File: metaprogramming.py    From mashumaro with Apache License 2.0 5 votes vote down vote up
def defaults(self):
        d = {}
        for ancestor in self.cls.__mro__[-1:0:-1]:
            if is_dataclass(ancestor):
                for field in getattr(ancestor, _FIELDS).values():
                    d[field.name] = field.default
        for name in self.__get_fields(recursive=False):
            d[name] = self.namespace.get(name, MISSING)
        return d 
Example #23
Source File: plugin.py    From galaxy-integrations-python-api with MIT License 5 votes vote down vote up
def default(self, o):  # pylint: disable=method-hidden
        if dataclasses.is_dataclass(o):
            # filter None values
            def dict_factory(elements):
                return {k: v for k, v in elements if v is not None}

            return dataclasses.asdict(o, dict_factory=dict_factory)
        if isinstance(o, Enum):
            return o.value
        return super().default(o) 
Example #24
Source File: test_validators_dataclass.py    From pydantic with MIT License 5 votes vote down vote up
def test_classmethod():
    @dataclass
    class MyDataclass:
        a: str

        @validator('a')
        def check_a(cls, v):
            assert cls is MyDataclass and is_dataclass(MyDataclass)
            return v

    m = MyDataclass(a='this is foobar good')
    assert m.a == 'this is foobar good'
    m.check_a('x') 
Example #25
Source File: history_request.py    From cadence-python with MIT License 5 votes vote down vote up
def default(self, o):
        if dataclasses.is_dataclass(o):
            return dataclasses.asdict(o)
        if isinstance(o, bytes):
            return str(o, 'utf-8')
        return super().default(o) 
Example #26
Source File: poll_decision_task.py    From cadence-python with MIT License 5 votes vote down vote up
def default(self, o):
        if dataclasses.is_dataclass(o):
            return dataclasses.asdict(o)
        if isinstance(o, bytes):
            return str(o, 'utf-8')
        return super().default(o) 
Example #27
Source File: to_abstract.py    From myia with MIT License 5 votes vote down vote up
def to_abstract(self, v: object, **kwargs):
    if is_dataclass(v):
        assert not isinstance(v, Function)
        new_args = {}
        for name, value in dataclass_fields(v).items():
            new_args[name] = self(value, **kwargs)
        return AbstractClass(type(v), new_args)
    else:
        return AbstractExternal({VALUE: v, TYPE: type(v)}) 
Example #28
Source File: hyperparams.py    From lm-human-preferences with MIT License 5 votes vote down vote up
def is_hparam_type(ty):
    if isinstance(ty, type) and issubclass(ty, HParams):
        assert is_dataclass(ty)
        return True
    else:
        return False 
Example #29
Source File: response.py    From selene-backend with GNU Affero General Public License v3.0 5 votes vote down vote up
def force_type(cls, rv, environ=None):
        if isinstance(rv, dict) or isinstance(rv, list) or is_dataclass(rv):
            reformat = coerce_response(rv)
            rv = jsonify(reformat)
        return super(SeleneResponse, cls).force_type(rv, environ) 
Example #30
Source File: json_encoder.py    From tdameritrade with Apache License 2.0 5 votes vote down vote up
def default(self, obj):
        if dataclasses.is_dataclass(obj) and hasattr(obj, "json"):
            return obj.json()
        return super().default(obj)