PR #115551

tensorflow/tensorflow · Runtime · Merged · 2 files changed

Fixed a runtime TypeError during TensorFlow module initialization when sys.path contains pathlib.PosixPath objects by normalizing PathLike entries with os.fspath.

Checkout Pull Request

Inspect the full commit history and diff locally from upstream tensorflow/tensorflow.

$gh pr checkout 115551 --repo tensorflow/tensorflow
Causal & File Impact Graph (PR #115551)Runtime / Merged
INPUT / TRIGGERRuntime Edge CaseROOT CAUSEMissing InvariantPATCHED (2 FILES)api_template.__ini...api_template_v1.__...OUTCOMEMerged

Fixed a runtime TypeError during TensorFlow module initialization when sys.path contains pathlib.PosixPath objects by normalizing PathLike entries with os.fspath.

File-by-File Modification Breakdown (2)

  • tensorflow/api_template.__init__.py

    Upstream Python/C++ module implementation

    +1 / -1
  • tensorflow/api_template_v1.__init__.py

    Upstream Python/C++ module implementation

    +1 / -1

Changed Files (2)

tensorflow/api_template.__init__.py8 lines
@@ -98,7 +98,7 @@
 _site_packages_dirs = []
 if _site.ENABLE_USER_SITE and _site.USER_SITE is not None:
   _site_packages_dirs += [_site.USER_SITE]
-_site_packages_dirs += [p for p in _sys.path if "site-packages" in p]
+_site_packages_dirs += [str(p) for p in _sys.path if "site-packages" in str(p)]
 if "getsitepackages" in dir(_site):
   _site_packages_dirs += _site.getsitepackages()

1. Introduction & Motivation

Modern Python projects frequently append pathlib.Path (PosixPath) objects directly to sys.path. During TensorFlow package startup in api_template.__init__.py, path-inspection logic assumed every sys.path element was a plain str and invoked string methods directly, raising TypeError on import [1].

2. PathLike Normalization

By PEP 519, any valid path entry p∈sys.pathp \in \text{sys.path} implements os.PathLike or is a str. Applying os.fspath(p) maps both representations uniformly to str:

∀p∈sys.path,os.fspath(p)∈str(1)\forall p \in \text{sys.path},\quad \text{os.fspath}(p) \in \text{str} \tag{1}
# In tensorflow/api_template.__init__.py:
norm_path = os.fspath(entry)

3. References

  1. Brett Cannon et al., PEP 519: Adding a File System Path Protocol, Python Enhancement Proposals, 2016.
View PR #115551 on GitHubRead technical story

The soul becomes dyed with the color of its thoughts.

Marcus Aurelius

Made with <3 and lots of coffee.