Given a file-like stream object, return its length in number of bytes without reading it into memory.
(stream: typing.Any)
| 93 | |
| 94 | |
| 95 | def peek_filelike_length(stream: typing.Any) -> int | None: |
| 96 | """ |
| 97 | Given a file-like stream object, return its length in number of bytes |
| 98 | without reading it into memory. |
| 99 | """ |
| 100 | try: |
| 101 | # Is it an actual file? |
| 102 | fd = stream.fileno() |
| 103 | # Yup, seems to be an actual file. |
| 104 | length = os.fstat(fd).st_size |
| 105 | except (AttributeError, OSError): |
| 106 | # No... Maybe it's something that supports random access, like `io.BytesIO`? |
| 107 | try: |
| 108 | # Assuming so, go to end of stream to figure out its length, |
| 109 | # then put it back in place. |
| 110 | offset = stream.tell() |
| 111 | length = stream.seek(0, os.SEEK_END) |
| 112 | stream.seek(offset) |
| 113 | except (AttributeError, OSError): |
| 114 | # Not even that? Sorry, we're doomed... |
| 115 | return None |
| 116 | |
| 117 | return length |
| 118 | |
| 119 | |
| 120 | class URLPattern: |
no outgoing calls
no test coverage detected