@@ -75,39 +75,47 @@ def _load_text(handle, encoding='utf-8'):
7575}
7676
7777
78- def load (url , cache = None , encoding = 'utf-8' ):
78+ def load (url_or_handle , cache = None , encoding = 'utf-8' ):
7979 """Load a file.
8080
8181 File format is inferred from url. File retrieval strategy is inferred from
8282 URL. Returned object type is inferred from url extension.
8383
8484 Args:
85- path : a (reachable) URL
85+ url_or_handle : a (reachable) URL, or an already open file handle
8686
8787 Raises:
8888 RuntimeError: If file extension or URL is not supported.
8989 """
90- _ , ext = os .path .splitext (url )
90+ is_handle = hasattr (url_or_handle , 'read' ) and hasattr (url_or_handle , 'name' )
91+ if is_handle :
92+ _ , ext = os .path .splitext (url_or_handle .name )
93+ else :
94+ _ , ext = os .path .splitext (url_or_handle )
9195 if not ext :
92- raise RuntimeError ("No extension in URL: " + url )
96+ raise RuntimeError ("No extension in URL: " + url_or_handle )
9397
9498 ext = ext .lower ()
9599 if ext in loaders :
96100 loader = loaders [ext ]
97101 message = "Using inferred loader '%s' due to passed file extension '%s'."
98102 log .debug (message , loader .__name__ [6 :], ext )
99- with read_handle (url , cache = cache ) as handle :
100- result = loader (handle , encoding = encoding )
103+ if is_handle :
104+ result = loader (url_or_handle , encoding = encoding )
105+ else :
106+ with read_handle (url_or_handle , cache = cache ) as handle :
107+ result = loader (handle , encoding = encoding )
101108 return result
102109 else :
110+ # TODO: handle 'handle' case? refactor?
103111 log .warn ("Unknown extension '%s', attempting to load as image." , ext )
104112 try :
105- with read_handle (url , cache = cache ) as handle :
113+ with read_handle (url_or_handle , cache = cache ) as handle :
106114 result = _load_img (handle )
107115 except Exception as e :
108116 message = "Could not load resource %s as image. Supported extensions: %s"
109- log .error (message , url , list (loaders ))
110- raise RuntimeError (message .format (url , list (loaders )))
117+ log .error (message , url_or_handle , list (loaders ))
118+ raise RuntimeError (message .format (url_or_handle , list (loaders )))
111119 else :
112120 log .info ("Unknown extension '%s' successfully loaded as image." , ext )
113121 return result
0 commit comments