Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/w3lib/util.py: 29%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

17 statements  

1from __future__ import annotations 

2 

3 

4def to_unicode( 

5 text: str | bytes, encoding: str | None = None, errors: str = "strict" 

6) -> str: 

7 """Return the unicode representation of a bytes object `text`. If `text` 

8 is already an unicode object, return it as-is.""" 

9 if isinstance(text, str): 

10 return text 

11 if not isinstance(text, (bytes, str)): 

12 raise TypeError( 

13 f"to_unicode must receive bytes or str, got {type(text).__name__}" 

14 ) 

15 if encoding is None: 

16 encoding = "utf-8" 

17 return text.decode(encoding, errors) 

18 

19 

20def to_bytes( 

21 text: str | bytes, encoding: str | None = None, errors: str = "strict" 

22) -> bytes: 

23 """Return the binary representation of `text`. If `text` 

24 is already a bytes object, return it as-is.""" 

25 if isinstance(text, bytes): 

26 return text 

27 if not isinstance(text, str): 

28 raise TypeError( 

29 f"to_bytes must receive str or bytes, got {type(text).__name__}" 

30 ) 

31 if encoding is None: 

32 encoding = "utf-8" 

33 return text.encode(encoding, errors)