Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions pyrsistent/_checked_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -510,8 +510,8 @@ def create(cls, source_data, _factory_fields=None, ignore_extra=False):
checked_value_type = next((t for t in value_types if issubclass(t, CheckedType)), None)

if checked_key_type or checked_value_type:
return cls(dict((checked_key_type.create(key) if checked_key_type and not any(isinstance(key, t) for t in key_types) else key,
checked_value_type.create(value) if checked_value_type and not any(isinstance(value, t) for t in value_types) else value)
return cls(dict((checked_key_type.create(key, ignore_extra=ignore_extra) if checked_key_type and not any(isinstance(key, t) for t in key_types) else key,
checked_value_type.create(value, ignore_extra=ignore_extra) if checked_value_type and not any(isinstance(value, t) for t in value_types) else value)
for key, value in source_data.items()))

return cls(source_data)
Expand Down
41 changes: 40 additions & 1 deletion tests/checked_map_test.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import pickle
import pytest
from pyrsistent import CheckedPMap, InvariantException, PMap, CheckedType, CheckedPSet, CheckedPVector, \
CheckedKeyTypeError, CheckedValueTypeError
CheckedKeyTypeError, CheckedValueTypeError, PRecord, field, pmap


class FloatToIntMap(CheckedPMap):
Expand Down Expand Up @@ -100,6 +100,45 @@ class IntSetToFloatVectorMap(CheckedPMap):

assert str(x) == "IntSetToFloatVectorMap({IntSet([1, 2]): FloatVector([1.25, 2.5])})"

def test_create_ignore_extra_forwarded_to_value_type():
class ValueRecord(PRecord):
a = field()

class StrToRecordMap(CheckedPMap):
__key_type__ = str
__value_type__ = ValueRecord

x = StrToRecordMap.create({'k': {'a': 1, 'extra': 2}}, ignore_extra=True)

assert x['k'] == ValueRecord(a=1)

def test_create_ignore_extra_forwarded_to_key_type():
class KeyRecord(PRecord):
a = field()

class RecordToIntMap(CheckedPMap):
__key_type__ = KeyRecord
__value_type__ = int

# A hashable PMap carrying an extra field is turned into KeyRecord via
# KeyRecord.create(); ignore_extra must be threaded through so the extra
# field is dropped instead of raising.
raw_key = pmap({'a': 1, 'extra': 2})
x = RecordToIntMap.create({raw_key: 5}, ignore_extra=True)

assert x[KeyRecord(a=1)] == 5

def test_create_ignore_extra_false_still_raises():
class ValueRecord(PRecord):
a = field()

class StrToRecordMap(CheckedPMap):
__key_type__ = str
__value_type__ = ValueRecord

with pytest.raises(AttributeError):
StrToRecordMap.create({'k': {'a': 1, 'extra': 2}})

def test_evolver_returns_same_instance_when_no_updates():
x = FloatToIntMap({1.25: 1, 2.25: 2})

Expand Down