Skip to content
Merged
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
1 change: 1 addition & 0 deletions fastcore/_modidx.py
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,7 @@
'fastcore.basics.ignore_exceptions.__exit__': ( 'basics.html#ignore_exceptions.__exit__',
'fastcore/basics.py'),
'fastcore.basics.in_': ('basics.html#in_', 'fastcore/basics.py'),
'fastcore.basics.init_args': ('basics.html#init_args', 'fastcore/basics.py'),
'fastcore.basics.instantiate': ('basics.html#instantiate', 'fastcore/basics.py'),
'fastcore.basics.is_array': ('basics.html#is_array', 'fastcore/basics.py'),
'fastcore.basics.joins': ('basics.html#joins', 'fastcore/basics.py'),
Expand Down
43 changes: 23 additions & 20 deletions fastcore/basics.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,21 +43,21 @@ def total(self:Point): return self.x + self.y
'true', 'NullType', 'tonull', 'get_class', 'mk_class', 'wrap_class', 'ignore_exceptions', 'exec_local',
'risinstance', 'ver2tuple', 'Inf', 'in_', 'ret_true', 'ret_false', 'stop', 'gen', 'chunked', 'otherwise',
'custom_dir', 'adict', 'AttrDict', 'AttrDictDefault', 'NS', 'get_annotations_ex', 'eval_type', 'type_hints',
'annotations', 'anno_ret', 'signature_ex', 'union2tuple', 'argnames', 'with_cast', 'store_attr', 'attrdict',
'properties', 'id_words', 'to_camel', 'to_pascal', 'to_kebab', 'to_snake', 'camel2words', 'camel2snake',
'snake2camel', 'humanize', 'class2attr', 'getcallable', 'getattrs', 'hasattrs', 'setattrs', 'try_attrs',
'DepProp', 'GetAttrBase', 'GetAttr', 'delegate_attr', 'ShowPrint', 'Int', 'Str', 'Float', 'partition',
'partition_dict', 'flatten', 'concat', 'strcat', 'detuplify', 'replicate', 'setify', 'merge', 'range_of',
'groupby', 'last_index', 'filter_dict', 'filter_keys', 'filter_values', 'cycle', 'zip_cycle', 'sorted_ex',
'not_', 'argwhere', 'filter_ex', 'renumerate', 'first', 'last', 'only', 'nested_attr', 'nested_setdefault',
'nested_callable', 'nested_idx', 'set_nested_idx', 'val2idx', 'uniqueify', 'loop_first_last', 'loop_first',
'loop_last', 'first_match', 'last_match', 'joins', 'fastuple', 'bind', 'mapt', 'map_ex', 'compose', 'maps',
'partialler', 'instantiate', 'using_attr', 'negate', 'fail_clean', 'dstar', 'copy_func', 'patch_to', 'patch',
'extend_enum', 'compile_re', 'ImportEnum', 'StrEnum', 'str_enum', 'ValEnum', 'Stateful', 'NotStr',
'PrettyString', 'even_mults', 'num_cpus', 'add_props', 'str2bool', 'str2int', 'str2float', 'str2list',
'str2date', 'str2dt', 'to_bool', 'to_int', 'to_float', 'to_list', 'to_date', 'typed', 'exec_new',
'exec_import', 'kindsort', 'sig_with_params', 'fdelegates', 'xdumps', 'revive_dates', 'lt', 'gt', 'le', 'ge',
'eq', 'ne', 'add', 'sub', 'mul', 'truediv', 'is_', 'is_not', 'mod']
'annotations', 'anno_ret', 'signature_ex', 'union2tuple', 'argnames', 'with_cast', 'store_attr', 'init_args',
'attrdict', 'properties', 'id_words', 'to_camel', 'to_pascal', 'to_kebab', 'to_snake', 'camel2words',
'camel2snake', 'snake2camel', 'humanize', 'class2attr', 'getcallable', 'getattrs', 'hasattrs', 'setattrs',
'try_attrs', 'DepProp', 'GetAttrBase', 'GetAttr', 'delegate_attr', 'ShowPrint', 'Int', 'Str', 'Float',
'partition', 'partition_dict', 'flatten', 'concat', 'strcat', 'detuplify', 'replicate', 'setify', 'merge',
'range_of', 'groupby', 'last_index', 'filter_dict', 'filter_keys', 'filter_values', 'cycle', 'zip_cycle',
'sorted_ex', 'not_', 'argwhere', 'filter_ex', 'renumerate', 'first', 'last', 'only', 'nested_attr',
'nested_setdefault', 'nested_callable', 'nested_idx', 'set_nested_idx', 'val2idx', 'uniqueify',
'loop_first_last', 'loop_first', 'loop_last', 'first_match', 'last_match', 'joins', 'fastuple', 'bind',
'mapt', 'map_ex', 'compose', 'maps', 'partialler', 'instantiate', 'using_attr', 'negate', 'fail_clean',
'dstar', 'copy_func', 'patch_to', 'patch', 'extend_enum', 'compile_re', 'ImportEnum', 'StrEnum', 'str_enum',
'ValEnum', 'Stateful', 'NotStr', 'PrettyString', 'even_mults', 'num_cpus', 'add_props', 'str2bool',
'str2int', 'str2float', 'str2list', 'str2date', 'str2dt', 'to_bool', 'to_int', 'to_float', 'to_list',
'to_date', 'typed', 'exec_new', 'exec_import', 'kindsort', 'sig_with_params', 'fdelegates', 'xdumps',
'revive_dates', 'lt', 'gt', 'le', 'ge', 'eq', 'ne', 'add', 'sub', 'mul', 'truediv', 'is_', 'is_not', 'mod']

# %% ../nbs/01_basics.ipynb #0e91ed82
from .imports import *
Expand Down Expand Up @@ -485,21 +485,18 @@ def _inner(*args, **kwargs):

# %% ../nbs/01_basics.ipynb #5cd34c5e
def _store_attr(self, anno, **attrs):
stored = getattr(self, '__stored_args__', None)
for n,v in attrs.items():
if n in anno: v = anno[n](v)
setattr(self, n, v)
if stored is not None: stored[n] = v


# %% ../nbs/01_basics.ipynb #59d6f1be
def store_attr(names=None, self=None, but='', cast=False, store_args=None, **attrs):
def store_attr(names=None, self=None, but='', cast=False, **attrs):
"Store params named in comma-separated `names` from calling context into attrs in `self`"
fr = sys._getframe(1)
args = argnames(fr, True)
if self: args = ('self', *args)
else: self = fr.f_locals[args[0]]
if store_args is None: store_args = not hasattr(self,'__slots__')
if store_args and not hasattr(self, '__stored_args__'): self.__stored_args__ = {}
anno = annotations(self) if cast else {}
if names and isinstance(names,str): names = re.split(', *', names)
ns = names if names is not None else getattr(self, '__slots__', args[1:])
Expand All @@ -509,6 +506,12 @@ def store_attr(names=None, self=None, but='', cast=False, store_args=None, **att
attrs = {k:v for k,v in attrs.items() if k not in but}
return _store_attr(self, anno, **attrs)

# %% ../nbs/01_basics.ipynb #50b2c270
def init_args(o):
"The `__init__` parameters of `o` that it holds as attributes, with their current values"
ps = inspect.signature(type(o).__init__).parameters
return {p:getattr(o,p) for p in ps if hasattr(o,p)}

# %% ../nbs/01_basics.ipynb #2648105d
def attrdict(o, *ks, default=None):
"Dict from each `k` in `ks` to `getattr(o,k)`"
Expand Down
30 changes: 21 additions & 9 deletions nbs/01_basics.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -2448,11 +2448,9 @@
"source": [
"#| export\n",
"def _store_attr(self, anno, **attrs):\n",
" stored = getattr(self, '__stored_args__', None)\n",
" for n,v in attrs.items():\n",
" if n in anno: v = anno[n](v)\n",
" setattr(self, n, v)\n",
" if stored is not None: stored[n] = v"
" setattr(self, n, v)\n"
]
},
{
Expand All @@ -2463,14 +2461,12 @@
"outputs": [],
"source": [
"#| export\n",
"def store_attr(names=None, self=None, but='', cast=False, store_args=None, **attrs):\n",
"def store_attr(names=None, self=None, but='', cast=False, **attrs):\n",
" \"Store params named in comma-separated `names` from calling context into attrs in `self`\"\n",
" fr = sys._getframe(1)\n",
" args = argnames(fr, True)\n",
" if self: args = ('self', *args)\n",
" else: self = fr.f_locals[args[0]]\n",
" if store_args is None: store_args = not hasattr(self,'__slots__')\n",
" if store_args and not hasattr(self, '__stored_args__'): self.__stored_args__ = {}\n",
" anno = annotations(self) if cast else {}\n",
" if names and isinstance(names,str): names = re.split(', *', names)\n",
" ns = names if names is not None else getattr(self, '__slots__', args[1:])\n",
Expand Down Expand Up @@ -2563,12 +2559,26 @@
" def __init__(self, a,b,c): store_attr()"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "50b2c270",
"metadata": {},
"outputs": [],
"source": [
"#| export\n",
"def init_args(o):\n",
" \"The `__init__` parameters of `o` that it holds as attributes, with their current values\"\n",
" ps = inspect.signature(type(o).__init__).parameters\n",
" return {p:getattr(o,p) for p in ps if hasattr(o,p)}"
]
},
{
"cell_type": "markdown",
"id": "9d202ce7",
"metadata": {},
"source": [
"In addition, it stores the attrs as a `dict` in `__stored_args__`, which you can use for display, logging, and so forth."
"`init_args` reads an object's constructor arguments back from its attributes, which is what a class using `store_attr` holds. Use it to display or log how an object was made:\n"
]
},
{
Expand All @@ -2578,7 +2588,9 @@
"metadata": {},
"outputs": [],
"source": [
"test_eq(t.__stored_args__, {'a':1, 'b':3, 'c':2})"
"t = T1(1,c=2,b=3)\n",
"test_eq(init_args(t), {'a':1, 'b':3, 'c':2})\n",
"init_args(t)\n"
]
},
{
Expand Down Expand Up @@ -2807,7 +2819,7 @@
"id": "73192c46",
"metadata": {},
"source": [
"You can also pass keywords to `store_attr`, which is identical to setting the attrs directly, but also stores them in `__stored_args__`."
"You can also pass keywords to `store_attr`, which is identical to setting the attrs directly:\n"
]
},
{
Expand Down