You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Add literal string support to include and exclude filters (#1068)
* Add literal string support to includer and exclude filters
* Add docs and changelog for new feature
* Fix typo in `typing_example`
* Add a note to document typo issues while using literal name strings as filter args
* Add more docs
* Add code mark for `AttributeError`
* Fix grammar error and upgrade `versionchanged` info
* Improve docs and examples from
hynek's comments
* Keep example cases the same
* More examples
* Apply suggestions from code review
Co-authored-by: chrysle <fritzihab@posteo.de>
---------
Co-authored-by: Hynek Schlawack <hs@ox.cx>
Co-authored-by: chrysle <fritzihab@posteo.de>
For the common case where you want to [`include`](attrs.filters.include) or [`exclude`](attrs.filters.exclude) certain types or attributes, *attrs* ships with a few helpers:
218
+
For the common case where you want to [`include`](attrs.filters.include) or [`exclude`](attrs.filters.exclude) certain types, string name or attributes, *attrs* ships with a few helpers:
219
219
220
220
```{doctest}
221
221
>>> from attrs import asdict, filters, fields
@@ -224,11 +224,12 @@ For the common case where you want to [`include`](attrs.filters.include) or [`ex
@@ -240,8 +241,34 @@ For the common case where you want to [`include`](attrs.filters.include) or [`ex
240
241
>>> asdict(C("foo", "2", 3),
241
242
... filter=filters.include(int, fields(C).x))
242
243
{'x': 'foo', 'z': 3}
244
+
245
+
>>> asdict(C("foo", "2", 3),
246
+
... filter=filters.include(fields(C).x, "z"))
247
+
{'x': 'foo', 'z': 3}
243
248
```
244
249
250
+
:::{note}
251
+
Though using string names directly is convenient, mistyping attribute names will silently do the wrong thing and neither Python nor your type checker can help you.
252
+
{func}`attrs.fields()` will raise an `AttributeError` when the field doesn't exist while literal string names won't.
253
+
Using {func}`attrs.fields()` to get attributes is worth being recommended in most cases.
0 commit comments