We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
numpy.save rejects unicode paths in Python 2.7
We've discovered this in our tests in [nipy/nipype](https://github.com/nipy/nipype) when 1.16 was released ([failing test](https://circleci.com/gh/nipy/nipype/7570)). It's unclear why it wasn't hitting our `--pre` tests, but it wasn't too tough to track down and reproduce.

It appears to have been introduced in #12157, which dropped an `if isinstance(file, basestring):` and explicitly checks `str` and `bytes`, which will resolve to `str` and `str` in Python 2, not `unicode` and `str`.

This is probably easily fixable on our end (just call `str()`), but in case you intend to support unicode paths, you should know about this.

Related: nipy/nipype#2855

<!-- Please describe the issue in detail here, and fill in the fields below -->

### Reproducing code example:

<!-- A short code example that reproduces the problem/missing feature. It should be
self-contained, i.e., possible to run as-is via 'python myproblem.py' -->

```python
from __future__ import unicode_literals
import numpy as np
np.save('abc.npy', np.array([0, 1, 2])
```

<!-- Remove these sections for a feature request -->

### Error message:


```
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-6-109f1bba4449> in <module>()
----> 1 np.save('abc.npy', np.array([0, 1, 2]))

/anaconda3/envs/python27/lib/python2.7/site-packages/numpy/lib/npyio.pyc in save(file, arr, allow_pickle, fix_imports)
    512         fid = file
    513     else:
--> 514         file = os_fspath(file)
    515         if not file.endswith('.npy'):
    516             file = file + '.npy'

/anaconda3/envs/python27/lib/python2.7/site-packages/numpy/compat/py3k.pyc in os_fspath(path)
    235             else:
    236                 raise TypeError("expected str, bytes or os.PathLike object, "
--> 237                                 "not " + path_type.__name__)
    238         if isinstance(path_repr, (str, bytes)):
    239             return path_repr

TypeError: expected str, bytes or os.PathLike object, not unicode
```
<!-- If you are reporting a segfault please include a GDB traceback, which you
can generate by following
https://github.com/numpy/numpy/blob/master/doc/source/dev/development_environment.rst#debugging -->

<!-- Full error message, if any (starting from line Traceback: ...) -->

### Numpy/Python version information:

<!-- Output from 'import sys, numpy; print(numpy.__version__, sys.version)' -->

```
('1.16.0', '2.7.15 |Anaconda, Inc.| (default, Dec 14 2018, 13:10:39) \n[GCC 4.2.1 Compatible Clang 4.0.1 (tags/RELEASE_401/final)]')
```

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `numpy/compat/py3k.py`
Content:
```
1 """
2 Python 3 compatibility tools.
3 
4 """
5 from __future__ import division, absolute_import, print_function
6 
7 __all__ = ['bytes', 'asbytes', 'isfileobj', 'getexception', 'strchar',
8            'unicode', 'asunicode', 'asbytes_nested', 'asunicode_nested',
9            'asstr', 'open_latin1', 'long', 'basestring', 'sixu',
10            'integer_types', 'is_pathlib_path', 'npy_load_module', 'Path',
11            'contextlib_nullcontext', 'os_fspath', 'os_PathLike']
12 
13 import sys
14 try:
15     from pathlib import Path, PurePath
16 except ImportError:
17     Path = PurePath = None
18 
19 if sys.version_info[0] >= 3:
20     import io
21 
22     long = int
23     integer_types = (int,)
24     basestring = str
25     unicode = str
26     bytes = bytes
27 
28     def asunicode(s):
29         if isinstance(s, bytes):
30             return s.decode('latin1')
31         return str(s)
32 
33     def asbytes(s):
34         if isinstance(s, bytes):
35             return s
36         return str(s).encode('latin1')
37 
38     def asstr(s):
39         if isinstance(s, bytes):
40             return s.decode('latin1')
41         return str(s)
42 
43     def isfileobj(f):
44         return isinstance(f, (io.FileIO, io.BufferedReader, io.BufferedWriter))
45 
46     def open_latin1(filename, mode='r'):
47         return open(filename, mode=mode, encoding='iso-8859-1')
48 
49     def sixu(s):
50         return s
51 
52     strchar = 'U'
53 
54 
55 else:
56     bytes = str
57     long = long
58     basestring = basestring
59     unicode = unicode
60     integer_types = (int, long)
61     asbytes = str
62     asstr = str
63     strchar = 'S'
64 
65     def isfileobj(f):
66         return isinstance(f, file)
67 
68     def asunicode(s):
69         if isinstance(s, unicode):
70             return s
71         return str(s).decode('ascii')
72 
73     def open_latin1(filename, mode='r'):
74         return open(filename, mode=mode)
75 
76     def sixu(s):
77         return unicode(s, 'unicode_escape')
78 
79 
80 def getexception():
81     return sys.exc_info()[1]
82 
83 def asbytes_nested(x):
84     if hasattr(x, '__iter__') and not isinstance(x, (bytes, unicode)):
85         return [asbytes_nested(y) for y in x]
86     else:
87         return asbytes(x)
88 
89 def asunicode_nested(x):
90     if hasattr(x, '__iter__') and not isinstance(x, (bytes, unicode)):
91         return [asunicode_nested(y) for y in x]
92     else:
93         return asunicode(x)
94 
95 def is_pathlib_path(obj):
96     """
97     Check whether obj is a pathlib.Path object.
98 
99     Prefer using `isinstance(obj, os_PathLike)` instead of this function.
100     """
101     return Path is not None and isinstance(obj, Path)
102 
103 # from Python 3.7
104 class contextlib_nullcontext(object):
105     """Context manager that does no additional processing.
106 
107     Used as a stand-in for a normal context manager, when a particular
108     block of code is only sometimes used with a normal context manager:
109 
110     cm = optional_cm if condition else nullcontext()
111     with cm:
112         # Perform operation, using optional_cm if condition is True
113     """
114 
115     def __init__(self, enter_result=None):
116         self.enter_result = enter_result
117 
118     def __enter__(self):
119         return self.enter_result
120 
121     def __exit__(self, *excinfo):
122         pass
123 
124 
125 if sys.version_info[0] >= 3 and sys.version_info[1] >= 4:
126     def npy_load_module(name, fn, info=None):
127         """
128         Load a module.
129 
130         .. versionadded:: 1.11.2
131 
132         Parameters
133         ----------
134         name : str
135             Full module name.
136         fn : str
137             Path to module file.
138         info : tuple, optional
139             Only here for backward compatibility with Python 2.*.
140 
141         Returns
142         -------
143         mod : module
144 
145         """
146         import importlib.machinery
147         return importlib.machinery.SourceFileLoader(name, fn).load_module()
148 else:
149     def npy_load_module(name, fn, info=None):
150         """
151         Load a module.
152 
153         .. versionadded:: 1.11.2
154 
155         Parameters
156         ----------
157         name : str
158             Full module name.
159         fn : str
160             Path to module file.
161         info : tuple, optional
162             Information as returned by `imp.find_module`
163             (suffix, mode, type).
164 
165         Returns
166         -------
167         mod : module
168 
169         """
170         import imp
171         import os
172         if info is None:
173             path = os.path.dirname(fn)
174             fo, fn, info = imp.find_module(name, [path])
175         else:
176             fo = open(fn, info[1])
177         try:
178             mod = imp.load_module(name, fo, fn, info)
179         finally:
180             fo.close()
181         return mod
182 
183 # backport abc.ABC
184 import abc
185 if sys.version_info[:2] >= (3, 4):
186     abc_ABC = abc.ABC
187 else:
188     abc_ABC = abc.ABCMeta('ABC', (object,), {'__slots__': ()})
189 
190 
191 # Backport os.fs_path, os.PathLike, and PurePath.__fspath__
192 if sys.version_info[:2] >= (3, 6):
193     import os
194     os_fspath = os.fspath
195     os_PathLike = os.PathLike
196 else:
197     def _PurePath__fspath__(self):
198         return str(self)
199 
200     class os_PathLike(abc_ABC):
201         """Abstract base class for implementing the file system path protocol."""
202 
203         @abc.abstractmethod
204         def __fspath__(self):
205             """Return the file system path representation of the object."""
206             raise NotImplementedError
207 
208         @classmethod
209         def __subclasshook__(cls, subclass):
210             if PurePath is not None and issubclass(subclass, PurePath):
211                 return True
212             return hasattr(subclass, '__fspath__')
213 
214 
215     def os_fspath(path):
216         """Return the path representation of a path-like object.
217         If str or bytes is passed in, it is returned unchanged. Otherwise the
218         os.PathLike interface is used to get the path representation. If the
219         path representation is not str or bytes, TypeError is raised. If the
220         provided path is not str, bytes, or os.PathLike, TypeError is raised.
221         """
222         if isinstance(path, (str, bytes)):
223             return path
224 
225         # Work from the object's type to match method resolution of other magic
226         # methods.
227         path_type = type(path)
228         try:
229             path_repr = path_type.__fspath__(path)
230         except AttributeError:
231             if hasattr(path_type, '__fspath__'):
232                 raise
233             elif PurePath is not None and issubclass(path_type, PurePath):
234                 return _PurePath__fspath__(path)
235             else:
236                 raise TypeError("expected str, bytes or os.PathLike object, "
237                                 "not " + path_type.__name__)
238         if isinstance(path_repr, (str, bytes)):
239             return path_repr
240         else:
241             raise TypeError("expected {}.__fspath__() to return str or bytes, "
242                             "not {}".format(path_type.__name__,
243                                             type(path_repr).__name__))
244
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/numpy/compat/py3k.py b/numpy/compat/py3k.py
--- a/numpy/compat/py3k.py
+++ b/numpy/compat/py3k.py
@@ -219,7 +219,7 @@
         path representation is not str or bytes, TypeError is raised. If the
         provided path is not str, bytes, or os.PathLike, TypeError is raised.
         """
-        if isinstance(path, (str, bytes)):
+        if isinstance(path, (unicode, bytes)):
             return path
 
         # Work from the object's type to match method resolution of other magic
@@ -235,7 +235,7 @@
             else:
                 raise TypeError("expected str, bytes or os.PathLike object, "
                                 "not " + path_type.__name__)
-        if isinstance(path_repr, (str, bytes)):
+        if isinstance(path_repr, (unicode, bytes)):
             return path_repr
         else:
             raise TypeError("expected {}.__fspath__() to return str or bytes, "

{"golden_diff": "diff --git a/numpy/compat/py3k.py b/numpy/compat/py3k.py\n--- a/numpy/compat/py3k.py\n+++ b/numpy/compat/py3k.py\n@@ -219,7 +219,7 @@\n         path representation is not str or bytes, TypeError is raised. If the\n         provided path is not str, bytes, or os.PathLike, TypeError is raised.\n         \"\"\"\n-        if isinstance(path, (str, bytes)):\n+        if isinstance(path, (unicode, bytes)):\n             return path\n \n         # Work from the object's type to match method resolution of other magic\n@@ -235,7 +235,7 @@\n             else:\n                 raise TypeError(\"expected str, bytes or os.PathLike object, \"\n                                 \"not \" + path_type.__name__)\n-        if isinstance(path_repr, (str, bytes)):\n+        if isinstance(path_repr, (unicode, bytes)):\n             return path_repr\n         else:\n             raise TypeError(\"expected {}.__fspath__() to return str or bytes, \"\n", "issue": "numpy.save rejects unicode paths in Python 2.7\nWe've discovered this in our tests in [nipy/nipype](https://github.com/nipy/nipype) when 1.16 was released ([failing test](https://circleci.com/gh/nipy/nipype/7570)). It's unclear why it wasn't hitting our `--pre` tests, but it wasn't too tough to track down and reproduce.\r\n\r\nIt appears to have been introduced in #12157, which dropped an `if isinstance(file, basestring):` and explicitly checks `str` and `bytes`, which will resolve to `str` and `str` in Python 2, not `unicode` and `str`.\r\n\r\nThis is probably easily fixable on our end (just call `str()`), but in case you intend to support unicode paths, you should know about this.\r\n\r\nRelated: nipy/nipype#2855\r\n\r\n<!-- Please describe the issue in detail here, and fill in the fields below -->\r\n\r\n### Reproducing code example:\r\n\r\n<!-- A short code example that reproduces the problem/missing feature. It should be\r\nself-contained, i.e., possible to run as-is via 'python myproblem.py' -->\r\n\r\n```python\r\nfrom __future__ import unicode_literals\r\nimport numpy as np\r\nnp.save('abc.npy', np.array([0, 1, 2])\r\n```\r\n\r\n<!-- Remove these sections for a feature request -->\r\n\r\n### Error message:\r\n\r\n\r\n```\r\n---------------------------------------------------------------------------\r\nTypeError                                 Traceback (most recent call last)\r\n<ipython-input-6-109f1bba4449> in <module>()\r\n----> 1 np.save('abc.npy', np.array([0, 1, 2]))\r\n\r\n/anaconda3/envs/python27/lib/python2.7/site-packages/numpy/lib/npyio.pyc in save(file, arr, allow_pickle, fix_imports)\r\n    512         fid = file\r\n    513     else:\r\n--> 514         file = os_fspath(file)\r\n    515         if not file.endswith('.npy'):\r\n    516             file = file + '.npy'\r\n\r\n/anaconda3/envs/python27/lib/python2.7/site-packages/numpy/compat/py3k.pyc in os_fspath(path)\r\n    235             else:\r\n    236                 raise TypeError(\"expected str, bytes or os.PathLike object, \"\r\n--> 237                                 \"not \" + path_type.__name__)\r\n    238         if isinstance(path_repr, (str, bytes)):\r\n    239             return path_repr\r\n\r\nTypeError: expected str, bytes or os.PathLike object, not unicode\r\n```\r\n<!-- If you are reporting a segfault please include a GDB traceback, which you\r\ncan generate by following\r\nhttps://github.com/numpy/numpy/blob/master/doc/source/dev/development_environment.rst#debugging -->\r\n\r\n<!-- Full error message, if any (starting from line Traceback: ...) -->\r\n\r\n### Numpy/Python version information:\r\n\r\n<!-- Output from 'import sys, numpy; print(numpy.__version__, sys.version)' -->\r\n\r\n```\r\n('1.16.0', '2.7.15 |Anaconda, Inc.| (default, Dec 14 2018, 13:10:39) \\n[GCC 4.2.1 Compatible Clang 4.0.1 (tags/RELEASE_401/final)]')\r\n```\n", "before_files": [{"content": "\"\"\"\nPython 3 compatibility tools.\n\n\"\"\"\nfrom __future__ import division, absolute_import, print_function\n\n__all__ = ['bytes', 'asbytes', 'isfileobj', 'getexception', 'strchar',\n           'unicode', 'asunicode', 'asbytes_nested', 'asunicode_nested',\n           'asstr', 'open_latin1', 'long', 'basestring', 'sixu',\n           'integer_types', 'is_pathlib_path', 'npy_load_module', 'Path',\n           'contextlib_nullcontext', 'os_fspath', 'os_PathLike']\n\nimport sys\ntry:\n    from pathlib import Path, PurePath\nexcept ImportError:\n    Path = PurePath = None\n\nif sys.version_info[0] >= 3:\n    import io\n\n    long = int\n    integer_types = (int,)\n    basestring = str\n    unicode = str\n    bytes = bytes\n\n    def asunicode(s):\n        if isinstance(s, bytes):\n            return s.decode('latin1')\n        return str(s)\n\n    def asbytes(s):\n        if isinstance(s, bytes):\n            return s\n        return str(s).encode('latin1')\n\n    def asstr(s):\n        if isinstance(s, bytes):\n            return s.decode('latin1')\n        return str(s)\n\n    def isfileobj(f):\n        return isinstance(f, (io.FileIO, io.BufferedReader, io.BufferedWriter))\n\n    def open_latin1(filename, mode='r'):\n        return open(filename, mode=mode, encoding='iso-8859-1')\n\n    def sixu(s):\n        return s\n\n    strchar = 'U'\n\n\nelse:\n    bytes = str\n    long = long\n    basestring = basestring\n    unicode = unicode\n    integer_types = (int, long)\n    asbytes = str\n    asstr = str\n    strchar = 'S'\n\n    def isfileobj(f):\n        return isinstance(f, file)\n\n    def asunicode(s):\n        if isinstance(s, unicode):\n            return s\n        return str(s).decode('ascii')\n\n    def open_latin1(filename, mode='r'):\n        return open(filename, mode=mode)\n\n    def sixu(s):\n        return unicode(s, 'unicode_escape')\n\n\ndef getexception():\n    return sys.exc_info()[1]\n\ndef asbytes_nested(x):\n    if hasattr(x, '__iter__') and not isinstance(x, (bytes, unicode)):\n        return [asbytes_nested(y) for y in x]\n    else:\n        return asbytes(x)\n\ndef asunicode_nested(x):\n    if hasattr(x, '__iter__') and not isinstance(x, (bytes, unicode)):\n        return [asunicode_nested(y) for y in x]\n    else:\n        return asunicode(x)\n\ndef is_pathlib_path(obj):\n    \"\"\"\n    Check whether obj is a pathlib.Path object.\n\n    Prefer using `isinstance(obj, os_PathLike)` instead of this function.\n    \"\"\"\n    return Path is not None and isinstance(obj, Path)\n\n# from Python 3.7\nclass contextlib_nullcontext(object):\n    \"\"\"Context manager that does no additional processing.\n\n    Used as a stand-in for a normal context manager, when a particular\n    block of code is only sometimes used with a normal context manager:\n\n    cm = optional_cm if condition else nullcontext()\n    with cm:\n        # Perform operation, using optional_cm if condition is True\n    \"\"\"\n\n    def __init__(self, enter_result=None):\n        self.enter_result = enter_result\n\n    def __enter__(self):\n        return self.enter_result\n\n    def __exit__(self, *excinfo):\n        pass\n\n\nif sys.version_info[0] >= 3 and sys.version_info[1] >= 4:\n    def npy_load_module(name, fn, info=None):\n        \"\"\"\n        Load a module.\n\n        .. versionadded:: 1.11.2\n\n        Parameters\n        ----------\n        name : str\n            Full module name.\n        fn : str\n            Path to module file.\n        info : tuple, optional\n            Only here for backward compatibility with Python 2.*.\n\n        Returns\n        -------\n        mod : module\n\n        \"\"\"\n        import importlib.machinery\n        return importlib.machinery.SourceFileLoader(name, fn).load_module()\nelse:\n    def npy_load_module(name, fn, info=None):\n        \"\"\"\n        Load a module.\n\n        .. versionadded:: 1.11.2\n\n        Parameters\n        ----------\n        name : str\n            Full module name.\n        fn : str\n            Path to module file.\n        info : tuple, optional\n            Information as returned by `imp.find_module`\n            (suffix, mode, type).\n\n        Returns\n        -------\n        mod : module\n\n        \"\"\"\n        import imp\n        import os\n        if info is None:\n            path = os.path.dirname(fn)\n            fo, fn, info = imp.find_module(name, [path])\n        else:\n            fo = open(fn, info[1])\n        try:\n            mod = imp.load_module(name, fo, fn, info)\n        finally:\n            fo.close()\n        return mod\n\n# backport abc.ABC\nimport abc\nif sys.version_info[:2] >= (3, 4):\n    abc_ABC = abc.ABC\nelse:\n    abc_ABC = abc.ABCMeta('ABC', (object,), {'__slots__': ()})\n\n\n# Backport os.fs_path, os.PathLike, and PurePath.__fspath__\nif sys.version_info[:2] >= (3, 6):\n    import os\n    os_fspath = os.fspath\n    os_PathLike = os.PathLike\nelse:\n    def _PurePath__fspath__(self):\n        return str(self)\n\n    class os_PathLike(abc_ABC):\n        \"\"\"Abstract base class for implementing the file system path protocol.\"\"\"\n\n        @abc.abstractmethod\n        def __fspath__(self):\n            \"\"\"Return the file system path representation of the object.\"\"\"\n            raise NotImplementedError\n\n        @classmethod\n        def __subclasshook__(cls, subclass):\n            if PurePath is not None and issubclass(subclass, PurePath):\n                return True\n            return hasattr(subclass, '__fspath__')\n\n\n    def os_fspath(path):\n        \"\"\"Return the path representation of a path-like object.\n        If str or bytes is passed in, it is returned unchanged. Otherwise the\n        os.PathLike interface is used to get the path representation. If the\n        path representation is not str or bytes, TypeError is raised. If the\n        provided path is not str, bytes, or os.PathLike, TypeError is raised.\n        \"\"\"\n        if isinstance(path, (str, bytes)):\n            return path\n\n        # Work from the object's type to match method resolution of other magic\n        # methods.\n        path_type = type(path)\n        try:\n            path_repr = path_type.__fspath__(path)\n        except AttributeError:\n            if hasattr(path_type, '__fspath__'):\n                raise\n            elif PurePath is not None and issubclass(path_type, PurePath):\n                return _PurePath__fspath__(path)\n            else:\n                raise TypeError(\"expected str, bytes or os.PathLike object, \"\n                                \"not \" + path_type.__name__)\n        if isinstance(path_repr, (str, bytes)):\n            return path_repr\n        else:\n            raise TypeError(\"expected {}.__fspath__() to return str or bytes, \"\n                            \"not {}\".format(path_type.__name__,\n                                            type(path_repr).__name__))\n", "path": "numpy/compat/py3k.py"}], "after_files": [{"content": "\"\"\"\nPython 3 compatibility tools.\n\n\"\"\"\nfrom __future__ import division, absolute_import, print_function\n\n__all__ = ['bytes', 'asbytes', 'isfileobj', 'getexception', 'strchar',\n           'unicode', 'asunicode', 'asbytes_nested', 'asunicode_nested',\n           'asstr', 'open_latin1', 'long', 'basestring', 'sixu',\n           'integer_types', 'is_pathlib_path', 'npy_load_module', 'Path',\n           'contextlib_nullcontext', 'os_fspath', 'os_PathLike']\n\nimport sys\ntry:\n    from pathlib import Path, PurePath\nexcept ImportError:\n    Path = PurePath = None\n\nif sys.version_info[0] >= 3:\n    import io\n\n    long = int\n    integer_types = (int,)\n    basestring = str\n    unicode = str\n    bytes = bytes\n\n    def asunicode(s):\n        if isinstance(s, bytes):\n            return s.decode('latin1')\n        return str(s)\n\n    def asbytes(s):\n        if isinstance(s, bytes):\n            return s\n        return str(s).encode('latin1')\n\n    def asstr(s):\n        if isinstance(s, bytes):\n            return s.decode('latin1')\n        return str(s)\n\n    def isfileobj(f):\n        return isinstance(f, (io.FileIO, io.BufferedReader, io.BufferedWriter))\n\n    def open_latin1(filename, mode='r'):\n        return open(filename, mode=mode, encoding='iso-8859-1')\n\n    def sixu(s):\n        return s\n\n    strchar = 'U'\n\n\nelse:\n    bytes = str\n    long = long\n    basestring = basestring\n    unicode = unicode\n    integer_types = (int, long)\n    asbytes = str\n    asstr = str\n    strchar = 'S'\n\n    def isfileobj(f):\n        return isinstance(f, file)\n\n    def asunicode(s):\n        if isinstance(s, unicode):\n            return s\n        return str(s).decode('ascii')\n\n    def open_latin1(filename, mode='r'):\n        return open(filename, mode=mode)\n\n    def sixu(s):\n        return unicode(s, 'unicode_escape')\n\n\ndef getexception():\n    return sys.exc_info()[1]\n\ndef asbytes_nested(x):\n    if hasattr(x, '__iter__') and not isinstance(x, (bytes, unicode)):\n        return [asbytes_nested(y) for y in x]\n    else:\n        return asbytes(x)\n\ndef asunicode_nested(x):\n    if hasattr(x, '__iter__') and not isinstance(x, (bytes, unicode)):\n        return [asunicode_nested(y) for y in x]\n    else:\n        return asunicode(x)\n\ndef is_pathlib_path(obj):\n    \"\"\"\n    Check whether obj is a pathlib.Path object.\n\n    Prefer using `isinstance(obj, os_PathLike)` instead of this function.\n    \"\"\"\n    return Path is not None and isinstance(obj, Path)\n\n# from Python 3.7\nclass contextlib_nullcontext(object):\n    \"\"\"Context manager that does no additional processing.\n\n    Used as a stand-in for a normal context manager, when a particular\n    block of code is only sometimes used with a normal context manager:\n\n    cm = optional_cm if condition else nullcontext()\n    with cm:\n        # Perform operation, using optional_cm if condition is True\n    \"\"\"\n\n    def __init__(self, enter_result=None):\n        self.enter_result = enter_result\n\n    def __enter__(self):\n        return self.enter_result\n\n    def __exit__(self, *excinfo):\n        pass\n\n\nif sys.version_info[0] >= 3 and sys.version_info[1] >= 4:\n    def npy_load_module(name, fn, info=None):\n        \"\"\"\n        Load a module.\n\n        .. versionadded:: 1.11.2\n\n        Parameters\n        ----------\n        name : str\n            Full module name.\n        fn : str\n            Path to module file.\n        info : tuple, optional\n            Only here for backward compatibility with Python 2.*.\n\n        Returns\n        -------\n        mod : module\n\n        \"\"\"\n        import importlib.machinery\n        return importlib.machinery.SourceFileLoader(name, fn).load_module()\nelse:\n    def npy_load_module(name, fn, info=None):\n        \"\"\"\n        Load a module.\n\n        .. versionadded:: 1.11.2\n\n        Parameters\n        ----------\n        name : str\n            Full module name.\n        fn : str\n            Path to module file.\n        info : tuple, optional\n            Information as returned by `imp.find_module`\n            (suffix, mode, type).\n\n        Returns\n        -------\n        mod : module\n\n        \"\"\"\n        import imp\n        import os\n        if info is None:\n            path = os.path.dirname(fn)\n            fo, fn, info = imp.find_module(name, [path])\n        else:\n            fo = open(fn, info[1])\n        try:\n            mod = imp.load_module(name, fo, fn, info)\n        finally:\n            fo.close()\n        return mod\n\n# backport abc.ABC\nimport abc\nif sys.version_info[:2] >= (3, 4):\n    abc_ABC = abc.ABC\nelse:\n    abc_ABC = abc.ABCMeta('ABC', (object,), {'__slots__': ()})\n\n\n# Backport os.fs_path, os.PathLike, and PurePath.__fspath__\nif sys.version_info[:2] >= (3, 6):\n    import os\n    os_fspath = os.fspath\n    os_PathLike = os.PathLike\nelse:\n    def _PurePath__fspath__(self):\n        return str(self)\n\n    class os_PathLike(abc_ABC):\n        \"\"\"Abstract base class for implementing the file system path protocol.\"\"\"\n\n        @abc.abstractmethod\n        def __fspath__(self):\n            \"\"\"Return the file system path representation of the object.\"\"\"\n            raise NotImplementedError\n\n        @classmethod\n        def __subclasshook__(cls, subclass):\n            if PurePath is not None and issubclass(subclass, PurePath):\n                return True\n            return hasattr(subclass, '__fspath__')\n\n\n    def os_fspath(path):\n        \"\"\"Return the path representation of a path-like object.\n        If str or bytes is passed in, it is returned unchanged. Otherwise the\n        os.PathLike interface is used to get the path representation. If the\n        path representation is not str or bytes, TypeError is raised. If the\n        provided path is not str, bytes, or os.PathLike, TypeError is raised.\n        \"\"\"\n        if isinstance(path, (unicode, bytes)):\n            return path\n\n        # Work from the object's type to match method resolution of other magic\n        # methods.\n        path_type = type(path)\n        try:\n            path_repr = path_type.__fspath__(path)\n        except AttributeError:\n            if hasattr(path_type, '__fspath__'):\n                raise\n            elif PurePath is not None and issubclass(path_type, PurePath):\n                return _PurePath__fspath__(path)\n            else:\n                raise TypeError(\"expected str, bytes or os.PathLike object, \"\n                                \"not \" + path_type.__name__)\n        if isinstance(path_repr, (unicode, bytes)):\n            return path_repr\n        else:\n            raise TypeError(\"expected {}.__fspath__() to return str or bytes, \"\n                            \"not {}\".format(path_type.__name__,\n                                            type(path_repr).__name__))\n", "path": "numpy/compat/py3k.py"}]}