Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 2 additions & 5 deletions Lib/importlib/resources/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,11 @@
"""

from ._common import (
Anchor,
Package,
as_file,
files,
Package,
Anchor,
)

from ._functional import (
contents,
is_resource,
Expand All @@ -23,10 +22,8 @@
read_binary,
read_text,
)

from .abc import ResourceReader


__all__ = [
'Package',
'Anchor',
Expand Down
20 changes: 10 additions & 10 deletions Lib/importlib/resources/_common.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import os
import pathlib
import tempfile
import functools
import contextlib
import types
import functools
import importlib
import inspect
import itertools
import os
import pathlib
import tempfile
import types
from typing import cast, Optional, Union

from typing import Union, Optional, cast
from .abc import ResourceReader, Traversable

Package = Union[types.ModuleType, str]
Expand All @@ -32,7 +32,7 @@ def get_resource_reader(package: types.ModuleType) -> Optional[ResourceReader]:
# zipimport.zipimporter does not support weak references, resulting in a
# TypeError. That seems terrible.
spec = package.__spec__
reader = getattr(spec.loader, 'get_resource_reader', None) # type: ignore[union-attr]
reader = getattr(spec.loader, "get_resource_reader", None) # type: ignore[union-attr]
if reader is None:
return None
return reader(spec.name) # type: ignore[union-attr]
Expand All @@ -50,7 +50,7 @@ def _(cand: str) -> types.ModuleType:

@resolve.register
def _(cand: None) -> types.ModuleType:
return resolve(_infer_caller().f_globals['__name__'])
return resolve(_infer_caller().f_globals["__name__"])


def _infer_caller():
Expand All @@ -62,7 +62,7 @@ def is_this_file(frame_info):
return frame_info.filename == stack[0].filename

def is_wrapper(frame_info):
return frame_info.function == 'wrapper'
return frame_info.function == "wrapper"

stack = inspect.stack()
not_this_file = itertools.filterfalse(is_this_file, stack)
Expand All @@ -87,7 +87,7 @@ def from_package(package: types.ModuleType):
@contextlib.contextmanager
def _tempfile(
reader,
suffix='',
suffix="",
# gh-93353: Keep a reference to call os.remove() in late Python
# finalization.
*,
Expand Down
9 changes: 6 additions & 3 deletions Lib/importlib/resources/_functional.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@

import warnings

from ._common import files, as_file

from ._common import as_file, files
from .abc import TraversalError

_MISSING = object()

Expand Down Expand Up @@ -42,7 +42,10 @@ def is_resource(anchor, *path_names):

Otherwise returns ``False``.
"""
return _get_resource(anchor, path_names).is_file()
try:
return _get_resource(anchor, path_names).is_file()
except TraversalError:
return False


def contents(anchor, *path_names):
Expand Down
38 changes: 29 additions & 9 deletions Lib/importlib/resources/abc.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,22 @@
import abc
import io
import itertools
import os
import pathlib
from typing import Any, BinaryIO, Iterable, Iterator, NoReturn, Text, Optional
from typing import runtime_checkable, Protocol
from typing import Union

from typing import (
Any,
BinaryIO,
Iterable,
Iterator,
Literal,
NoReturn,
Optional,
Protocol,
Text,
TextIO,
Union,
overload,
runtime_checkable,
)

StrPath = Union[str, os.PathLike[str]]

Expand Down Expand Up @@ -82,11 +92,13 @@ def read_bytes(self) -> bytes:
with self.open('rb') as strm:
return strm.read()

def read_text(self, encoding: Optional[str] = None) -> str:
def read_text(
self, encoding: Optional[str] = None, errors: Optional[str] = None
) -> str:
"""
Read contents of self as text
"""
with self.open(encoding=encoding) as strm:
with self.open(encoding=encoding, errors=errors) as strm:
return strm.read()

@abc.abstractmethod
Expand Down Expand Up @@ -132,8 +144,16 @@ def __truediv__(self, child: StrPath) -> "Traversable":
"""
return self.joinpath(child)

@overload
def open(self, mode: Literal['r'] = 'r', *args: Any, **kwargs: Any) -> TextIO: ...

@overload
def open(self, mode: Literal['rb'], *args: Any, **kwargs: Any) -> BinaryIO: ...

@abc.abstractmethod
def open(self, mode='r', *args, **kwargs):
def open(
self, mode: str = 'r', *args: Any, **kwargs: Any
) -> Union[TextIO, BinaryIO]:
"""
mode may be 'r' or 'rb' to open as text or binary. Return a handle
suitable for reading (same as pathlib.Path.open).
Expand All @@ -160,7 +180,7 @@ class TraversableResources(ResourceReader):
def files(self) -> "Traversable":
"""Return a Traversable object for the loaded package."""

def open_resource(self, resource: StrPath) -> io.BufferedReader:
def open_resource(self, resource: StrPath) -> BinaryIO:
return self.files().joinpath(resource).open('rb')

def resource_path(self, resource: Any) -> NoReturn:
Expand Down
3 changes: 1 addition & 2 deletions Lib/importlib/resources/readers.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,14 @@
import collections
import contextlib
import itertools
import pathlib
import operator
import pathlib
import re
import warnings
import zipfile
from collections.abc import Iterator

from . import abc

from ._itertools import only


Expand Down
8 changes: 2 additions & 6 deletions Lib/test/test_importlib/resources/_path.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,6 @@
import pathlib
import functools

from typing import Dict, Union
from typing import runtime_checkable
from typing import Protocol

import pathlib
from typing import Dict, Protocol, Union, runtime_checkable

####
# from jaraco.path 3.7.1
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
import importlib.resources as resources
import io
import unittest

from importlib import resources

from importlib.resources._adapters import (
CompatibilityFiles,
wrap_spec,
Expand Down
2 changes: 1 addition & 1 deletion Lib/test/test_importlib/resources/test_contents.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import importlib.resources as resources
import unittest
from importlib import resources

from . import util

Expand Down
8 changes: 4 additions & 4 deletions Lib/test/test_importlib/resources/test_custom.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import unittest
import contextlib
import importlib.resources as resources
import pathlib
import unittest
from importlib.resources import abc
from importlib.resources.abc import ResourceReader, TraversableResources

from test.support import os_helper

from importlib import resources
from importlib.resources import abc
from importlib.resources.abc import TraversableResources, ResourceReader
from . import util


Expand Down
17 changes: 10 additions & 7 deletions Lib/test/test_importlib/resources/test_files.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
import contextlib
import importlib
import importlib.resources as resources
import pathlib
import py_compile
import textwrap
import unittest
import warnings
import importlib
import contextlib

from importlib import resources
from importlib.resources.abc import Traversable

from test.support import import_helper, os_helper

from . import util
from test.support import os_helper, import_helper


@contextlib.contextmanager
Expand Down Expand Up @@ -62,7 +63,7 @@ def test_non_paths_in_dunder_path(self):
to cause the ``PathEntryFinder`` to be called when searching
for packages. In that case, resources should still be loadable.
"""
import namespacedata01
import namespacedata01 # type: ignore[import-not-found]

namespacedata01.__path__.append(
'__editable__.sample_namespace-1.0.finder.__path_hook__'
Expand Down Expand Up @@ -153,7 +154,9 @@ def _compile_importlib(self):
sources = pathlib.Path(resources.__file__).parent

for source_path in sources.glob('**/*.py'):
c_path = c_resources.joinpath(source_path.relative_to(sources)).with_suffix('.pyc')
c_path = c_resources.joinpath(source_path.relative_to(sources)).with_suffix(
'.pyc'
)
py_compile.compile(source_path, c_path)
self.fixtures.enter_context(import_helper.DirsOnSysPath(bin_site))

Expand Down
Loading
Loading