Skip to content

Commit

Permalink
add the ability to get attributes rather than just objects
Browse files Browse the repository at this point in the history
  • Loading branch information
cjw296 committed Nov 22, 2018
1 parent de4f2be commit 8a5d744
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 2 deletions.
14 changes: 12 additions & 2 deletions chide/collection.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ def _attrs(self, type_, attrs, nest):
computed_attrs.update(attrs)
return computed_attrs

def make(self, type_, **attrs):
def attributes(self, type_, **attrs):
"""
Make a sample object of the specified ``type_`` using the default
attributes for that type in this :class:`Collection`.
Expand All @@ -28,4 +28,14 @@ def make(self, type_, **attrs):
before being used with ``type_`` to instantiate and return a new
sample object.
"""
return type_(**self._attrs(type_, attrs, self.make))
return self._attrs(type_, attrs, self.make)

def make(self, type_, **attrs):
"""
Make the attributes for a sample object of the specified ``type_``
using the default attributes for that type in this :class:`Collection`.
The ``attrs`` mapping will be overlayed onto the sample attributes
and returned as a :class:`dict`.
"""
return type_(**self.attributes(type_, **attrs))
28 changes: 28 additions & 0 deletions docs/use.rst
Original file line number Diff line number Diff line change
Expand Up @@ -149,3 +149,31 @@ This because the :func:`identify` function above returns ``None`` for all types
other than :class:`Address`. Returning ``None`` from :func:`identify` is the
way to indicate that a new object should be returned, regardless of the
attributes it has.

Creating attributes for objects
--------------------------------

Given this collection:

.. code-block:: python
from chide import Collection
samples = Collection({
ClassOne: {'x': 1, 'y': 2},
ClassTwo: {'a': 1, 'b': ClassOne},
})
We can also create attributes to make a sample object:

>>> attrs = samples.attributes(ClassOne)
>>> attrs['x']
1
>>> attrs['y']
2

>>> attrs = samples.attributes(ClassTwo)
>>> attrs['a']
1
>>> attrs['b']
<ClassOne object at ...>

0 comments on commit 8a5d744

Please sign in to comment.