From 30a30972a6610cf033631afd2d168421586c5a31 Mon Sep 17 00:00:00 2001 From: Nicola Soranzo Date: Thu, 1 Feb 2018 00:41:02 +0000 Subject: [PATCH] Add file_types to allow checking if variable isinstance of file Fix https://github.com/benjaminp/six/issues/61 Implementation similar to https://stackoverflow.com/a/36321030 --- documentation/index.rst | 6 ++++++ six.py | 4 +++- test_six.py | 6 ++++++ 3 files changed, 15 insertions(+), 1 deletion(-) diff --git a/documentation/index.rst b/documentation/index.rst index e86e3f86f..59fad3395 100644 --- a/documentation/index.rst +++ b/documentation/index.rst @@ -78,6 +78,12 @@ Six provides constants that may differ between Python versions. Ones ending :func:`py3:bytes` in Python 3. +.. data:: file_types + + Possible types for files. This is :func:`py2:file` and :func:`py2:io.IOBase` + in Python 2 and just :func:`py3:io.IOBase` in Python 3. + + .. data:: MAXSIZE The maximum size of a container like :func:`py3:list` or :func:`py3:dict`. diff --git a/six.py b/six.py index 8d9ac41a8..cedfe790c 100644 --- a/six.py +++ b/six.py @@ -23,6 +23,7 @@ from __future__ import absolute_import import functools +import io import itertools import operator import sys @@ -43,6 +44,7 @@ class_types = type, text_type = str binary_type = bytes + file_types = (io.IOBase, ) MAXSIZE = sys.maxsize else: @@ -51,6 +53,7 @@ class_types = (type, types.ClassType) text_type = unicode binary_type = str + file_types = (file, io.IOBase) if sys.platform.startswith("java"): # Jython always uses 32 bits. @@ -634,7 +637,6 @@ def u(s): byte2int = operator.itemgetter(0) indexbytes = operator.getitem iterbytes = iter - import io StringIO = io.StringIO BytesIO = io.BytesIO _assertCountEqual = "assertCountEqual" diff --git a/test_six.py b/test_six.py index 980cdf3aa..c432724bf 100644 --- a/test_six.py +++ b/test_six.py @@ -73,6 +73,12 @@ def test_binary_type(): assert type(six.b("hi")) is six.binary_type +def test_file_types(): + import tempfile + with tempfile.TemporaryFile() as fh: + assert isinstance(fh, six.file_types) + + def test_MAXSIZE(): try: # This shouldn't raise an overflow error.