Skip to content

Commit

Permalink
Add note on attribute extension defaults (resolves #1587)
Browse files Browse the repository at this point in the history
  • Loading branch information
ines committed Nov 17, 2017
1 parent 954f8cc commit c3051e9
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
5 changes: 4 additions & 1 deletion website/usage/_processing-pipelines/_custom-components.jade
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,10 @@ p
| Set a default value for an attribute, which can be overwritten
| manually at any time. Attribute extensions work like "normal"
| variables and are the quickest way to store arbitrary information
| on a #[code Doc], #[code Span] or #[code Token].
| on a #[code Doc], #[code Span] or #[code Token]. Attribute defaults
| behaves just like argument defaults
| #[+a("http://docs.python-guide.org/en/latest/writing/gotchas/#mutable-default-arguments") in Python functions],
| and should not be used for mutable values like dictionaries or lists.

+code-wrapper
+code.
Expand Down
18 changes: 18 additions & 0 deletions website/usage/_processing-pipelines/_extensions.jade
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,24 @@ p
if token.text in ('apple', 'orange'):
token._.set('is_fruit', True)

+item
| When using #[strong mutable values] like dictionaries or lists as
| the #[code default] argument, keep in mind that they behave just like
| mutable default arguments
| #[+a("http://docs.python-guide.org/en/latest/writing/gotchas/#mutable-default-arguments") in Python functions].
| This can easily cause unintended results, like the same value being
| set on #[em all] objects instead of only one particular instance.
| In most cases, it's better to use #[strong getters and setters], and
| only set the #[code default] for boolean or string values.

+code-wrapper
+code-new.
Doc.set_extension('fruits', getter=get_fruits, setter=set_fruits)

+code-old.
Doc.set_extension('fruits', default={})
doc._.fruits['apple'] = u'🍎' # all docs now have {'apple': u'🍎'}

+item
| Always add your custom attributes to the #[strong global] #[code Doc]
| #[code Token] or #[code Span] objects, not a particular instance of
Expand Down

0 comments on commit c3051e9

Please sign in to comment.