Repository navigation
Commit da189bd
authored
Use Union[bytes, Text] instead of AnyStr
It seems that AnyStr has the main advantage of ensuring that multiple arguments (or argument(s) and return values) have the same type (i.e. `str` and `bytes` are both okay but shouldn't be mixed). However it makes it significantly more difficult to cast to a single type.
With a Union, something like:
```python
def foo(a: Union[bytes, Text]) -> Text:
if isinstance(a, bytes):
a = a.decode()
return "Hello, " + a
```
works fine. With AnyStr, you have to define a new intermediate variable, something like:
```python
def foo(a: AnyStr) -> str:
if isinstance(a, bytes):
b = a.decode()
else:
b = a
return "Hello, " + b
```
If there's no advantage to using AnyStr (since there's no other AnyStr argument or return value), I think the Union would be simpler, have no significant disadvantage, and there is [precedent for similar changes](python#1054).
> It's only the case that if there's exactly one parameter of type exactly AnyStr, and no other use of AnyStr in the signature, then Union[str, bytes] should be acceptable.
- [gvanrossum](python#439 (comment))
Discussion:
- python#1054
- python/mypy#1141
- python#4391 parent 7073bc0 commit da189bd
1 file changed
Lines changed: 3 additions & 3 deletions
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1 | 1 | | |
2 | | - | |
| 2 | + | |
3 | 3 | | |
4 | 4 | | |
5 | 5 | | |
| |||
15 | 15 | | |
16 | 16 | | |
17 | 17 | | |
18 | | - | |
| 18 | + | |
19 | 19 | | |
20 | 20 | | |
21 | 21 | | |
22 | | - | |
| 22 | + | |
23 | 23 | | |
24 | 24 | | |
0 commit comments