@@ -66,13 +66,19 @@ def _get_resource_reader(
6666 return None
6767
6868
69+ def _check_location (package ):
70+ if package .__spec__ .origin is None or not package .__spec__ .has_location :
71+ raise FileNotFoundError (f'Package has no location { package !r} ' )
72+
73+
6974def open_binary (package : Package , resource : Resource ) -> BinaryIO :
7075 """Return a file-like object opened for binary reading of the resource."""
7176 resource = _normalize_path (resource )
7277 package = _get_package (package )
7378 reader = _get_resource_reader (package )
7479 if reader is not None :
7580 return reader .open_resource (resource )
81+ _check_location (package )
7682 absolute_package_path = os .path .abspath (package .__spec__ .origin )
7783 package_path = os .path .dirname (absolute_package_path )
7884 full_path = os .path .join (package_path , resource )
@@ -106,6 +112,7 @@ def open_text(package: Package,
106112 reader = _get_resource_reader (package )
107113 if reader is not None :
108114 return TextIOWrapper (reader .open_resource (resource ), encoding , errors )
115+ _check_location (package )
109116 absolute_package_path = os .path .abspath (package .__spec__ .origin )
110117 package_path = os .path .dirname (absolute_package_path )
111118 full_path = os .path .join (package_path , resource )
@@ -172,6 +179,8 @@ def path(package: Package, resource: Resource) -> Iterator[Path]:
172179 return
173180 except FileNotFoundError :
174181 pass
182+ else :
183+ _check_location (package )
175184 # Fall-through for both the lack of resource_path() *and* if
176185 # resource_path() raises FileNotFoundError.
177186 package_directory = Path (package .__spec__ .origin ).parent
@@ -232,9 +241,9 @@ def contents(package: Package) -> Iterator[str]:
232241 yield from reader .contents ()
233242 return
234243 # Is the package a namespace package? By definition, namespace packages
235- # cannot have resources.
236- if ( package . __spec__ . origin == 'namespace' and
237- not package .__spec__ .has_location ) :
244+ # cannot have resources. We could use _check_location() and catch the
245+ # exception, but that's extra work, so just inline the check.
246+ if package . __spec__ . origin is None or not package .__spec__ .has_location :
238247 return []
239248 package_directory = Path (package .__spec__ .origin ).parent
240249 yield from os .listdir (str (package_directory ))
0 commit comments