@@ -66,13 +66,19 @@ def _get_resource_reader(
66
66
return None
67
67
68
68
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
+
69
74
def open_binary (package : Package , resource : Resource ) -> BinaryIO :
70
75
"""Return a file-like object opened for binary reading of the resource."""
71
76
resource = _normalize_path (resource )
72
77
package = _get_package (package )
73
78
reader = _get_resource_reader (package )
74
79
if reader is not None :
75
80
return reader .open_resource (resource )
81
+ _check_location (package )
76
82
absolute_package_path = os .path .abspath (package .__spec__ .origin )
77
83
package_path = os .path .dirname (absolute_package_path )
78
84
full_path = os .path .join (package_path , resource )
@@ -106,6 +112,7 @@ def open_text(package: Package,
106
112
reader = _get_resource_reader (package )
107
113
if reader is not None :
108
114
return TextIOWrapper (reader .open_resource (resource ), encoding , errors )
115
+ _check_location (package )
109
116
absolute_package_path = os .path .abspath (package .__spec__ .origin )
110
117
package_path = os .path .dirname (absolute_package_path )
111
118
full_path = os .path .join (package_path , resource )
@@ -172,6 +179,8 @@ def path(package: Package, resource: Resource) -> Iterator[Path]:
172
179
return
173
180
except FileNotFoundError :
174
181
pass
182
+ else :
183
+ _check_location (package )
175
184
# Fall-through for both the lack of resource_path() *and* if
176
185
# resource_path() raises FileNotFoundError.
177
186
package_directory = Path (package .__spec__ .origin ).parent
@@ -232,9 +241,9 @@ def contents(package: Package) -> Iterator[str]:
232
241
yield from reader .contents ()
233
242
return
234
243
# 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 :
238
247
return []
239
248
package_directory = Path (package .__spec__ .origin ).parent
240
249
yield from os .listdir (str (package_directory ))
0 commit comments