_fileno.py 799 B

123456789101112131415161718192021222324
  1. from __future__ import annotations
  2. from typing import IO, Callable
  3. def get_fileno(file_like: IO[str]) -> int | None:
  4. """Get fileno() from a file, accounting for poorly implemented file-like objects.
  5. Args:
  6. file_like (IO): A file-like object.
  7. Returns:
  8. int | None: The result of fileno if available, or None if operation failed.
  9. """
  10. fileno: Callable[[], int] | None = getattr(file_like, "fileno", None)
  11. if fileno is not None:
  12. try:
  13. return fileno()
  14. except Exception:
  15. # `fileno` is documented as potentially raising a OSError
  16. # Alas, from the issues, there are so many poorly implemented file-like objects,
  17. # that `fileno()` can raise just about anything.
  18. return None
  19. return None