latest (dev)
Copy
Latest development documentation · Updated 2026-10-08
tensorplay.package API
Functions 2
is_from_package
functionFull reference ↗is_mangled
functionFull reference ↗Classes 7
Directory
classFull reference ↗- class tensorplay.package.Directory(name: str, is_dir: bool)[source]
A file structure representation. Organized as Directory nodes that have lists of their Directory children. Directories for a package are created by calling
PackageImporter.file_structure().
GlobGroup
classFull reference ↗- class tensorplay.package.GlobGroup(include: str | Iterable[str], *, exclude: str | Iterable[str] = (), separator: str = '.')[source]
A set of patterns that candidate strings will be matched against.
A candidate is composed of a list of segments separated by
separator, e.g."foo.bar.baz".- A pattern contains one or more segments. Segments can be:
A literal string (e.g.
"foo"), which matches exactly.A string containing a wildcard (e.g.
"tensorplay*", or"foo*baz*"). The wildcard matches any string, including the empty string.A double wildcard (
"**"). This matches against zero or more complete segments.
Examples
tensorplay.**: matchestensorplayand all its submodules, e.g.tensorplay.nnandtensorplay.nn.functional.tensorplay.*: matchestensorplay.nnortensorplay.utils, but nottensorplay.nn.functional.tensorplay*.**: matchestensorplay,tensorplay_vision, and all their submodules.A candidate will match the
GlobGroupif it matches any of theincludepatterns and none of theexcludepatterns.- Parameters:
include (str | Iterable[str]) – A string or list of strings, each representing a pattern to be matched against. A candidate will match if it matches any include pattern
exclude (str | Iterable[str]) – A string or list of strings, each representing a pattern to be matched against. A candidate will be excluded from matching if it matches any exclude pattern.
separator (str) – A string that delimits segments in candidates and patterns. By default this is “.” which corresponds to how modules are named in Python. Another common value for this is “/”, which is the Unix path separator.
Importer
classFull reference ↗- class tensorplay.package.Importer[source]
Represents an environment to import modules from.
By default, you can figure out what module an object belongs by checking __module__ and importing the result using __import__ or importlib.import_module.
tensorplay.package introduces module importers other than the default one. Each PackageImporter introduces a new namespace. Potentially a single name (e.g. ‘foo.bar’) is present in multiple namespaces.
- It supports two main operations:
import_module: module_name -> module object get_name: object -> (parent module name, name of obj within module)
- The guarantee is that following round-trip will succeed or throw an ObjNotFoundError/ObjMisMatchError.
module_name, obj_name = env.get_name(obj) module = env.import_module(module_name) obj2 = getattr(module, obj_name) assert obj1 is obj2
- get_name(obj: Any, name: str | None = None) tuple[str, str][source]
Given an object, return a name that can be used to retrieve the object from this environment.
- Parameters:
obj – An object to get the module-environment-relative name for.
name – If set, use this name instead of looking up
__name__or__qualname__onobj. This is only here to match how Pickler handles__reduce__functions that return a string, don’t use otherwise.
- Returns:
A tuple (parent_module_name, attr_name) that can be used to retrieve
objfrom this environment. To use it:mod = importer.import_module(parent_module_name) obj = getattr(mod, attr_name)- Raises:
ObjNotFoundError – we couldn’t retrieve
objby name.ObjMisMatchError – we found a different object with the same name as
obj.
- abstractmethod import_module(module_name: str) ModuleType[source]
Import module_name from this environment.
The contract is the same as for importlib.import_module.
- whichmodule(obj: Any, name: str) str[source]
Find the module name an object belongs to.
This should be considered internal for end-users, but developers of an importer can override it to customize the behavior.
Based on the classic pickle.py approach, but modified to exclude the search into sys.modules.
OrderedImporter
classFull reference ↗- class tensorplay.package.OrderedImporter(*args)[source]
A compound importer that takes a list of importers and tries them one at a time.
The first importer in the list that returns a result “wins”.
PackageExporter
classFull reference ↗- class tensorplay.package.PackageExporter(f: str | ~os.PathLike[str] | ~typing.IO[bytes], importer: ~tensorplay.package.importer.Importer | ~collections.abc.Sequence[~tensorplay.package.importer.Importer] = <tensorplay.package.importer._SysImporter object>, debug: bool = False)[source]
Exporters allow you to write packages of code, pickled Python data, and arbitrary binary and text resources into a self-contained package.
Imports can load this code in a hermetic way, such that code is loaded from the package rather than the normal Python import system. This allows for the packaging of model code and data so that it can be run on a server or used in the future for transfer learning.
The code contained in packages is copied file-by-file from the original source when it is created, and the file format is a specially organized zip file. Future users of the package can unzip the package, and edit the code in order to perform custom modifications to it.
The importer for packages ensures that code in the module can only be loaded from within the package, except for modules explicitly listed as external using
extern(). The fileextern_modulesin the zip archive lists all the modules that a package externally depends on. This prevents “implicit” dependencies where the package runs locally because it is importing a locally-installed package, but then fails when the package is copied to another machine.When source code is added to the package, the exporter can optionally scan it for further code dependencies (
dependencies=True). It looks for import statements, resolves relative references to qualified module names, and performs an action specified by the user (See:extern(),mock(), andintern()).Only plain Python modules are supported: C extension modules and other compiled or interpreter-specific artifacts cannot be interned. Objects embedded with
save_pickle()serialize tensors through tensorplay’s own pickling support.- add_dependency(module_name: str, dependencies=True)[source]
Given a module, add it to the dependency graph according to patterns specified by the user.
- all_paths(src: str, dst: str) str[source]
- Return a dot representation of the subgraph
that has all paths from src to dst.
- Returns:
A dot representation containing all paths from src to dst. (https://graphviz.org/doc/info/lang.html)
- close()[source]
Write the package to the filesystem. Any calls after
close()are now invalid. It is preferable to use resource guard syntax instead:with PackageExporter("file.zip") as e: ...
- denied_modules() list[str][source]
Return all modules that are currently denied.
- Returns:
A list containing the names of modules which will be denied in this package.
- deny(include: str | Iterable[str], *, exclude: str | Iterable[str] = ())[source]
Blocklist modules whose names match the given glob patterns from the list of modules the package can import. If a dependency on any matching packages is found, a
PackagingErroris raised.- Parameters:
include (list[str] | str) – A string e.g.
"my_package.my_subpackage", or list of strings for the names of the modules to be externed. This can also be a glob-style pattern, as described inmock().exclude (list[str] | str) – An optional pattern that excludes some patterns that match the include string.
- dependency_graph_string() str[source]
Returns digraph string representation of dependencies in package.
- Returns:
A string representation of dependencies in package.
- extern(include: str | Iterable[str], *, exclude: str | Iterable[str] = (), allow_empty: bool = True)[source]
Include
modulein the list of external modules the package can import. This will prevent dependency discovery from saving it in the package. The importer will load an external module directly from the standard import system. Code for extern modules must also exist in the process loading the package.- Parameters:
include (list[str] | str) – A string e.g.
"my_package.my_subpackage", or list of strings for the names of the modules to be externed. This can also be a glob-style pattern, as described inmock().exclude (list[str] | str) – An optional pattern that excludes some patterns that match the include string.
allow_empty (bool) – An optional flag that specifies whether the extern modules specified by this call to the
externmethod must be matched to some module during packaging. If an extern module glob pattern is added withallow_empty=False, andclose()is called (either explicitly or via__exit__) before any modules match that pattern, an exception is thrown. Ifallow_empty=True, no such exception is thrown.
- externed_modules() list[str][source]
Return all modules that are currently externed.
- Returns:
A list containing the names of modules which will be externed in this package.
- get_rdeps(module_name: str) list[str][source]
Return a list of all modules which depend on the module
module_name.- Returns:
A list containing the names of modules which depend on
module_name.
- get_unique_id() str[source]
Get an id. This id is guaranteed to only be handed out once for this package.
- intern(include: str | Iterable[str], *, exclude: str | Iterable[str] = (), allow_empty: bool = True)[source]
Specify modules that should be packaged. A module must match some
internpattern in order to be included in the package and have its dependencies processed recursively.- Parameters:
include (list[str] | str) – A string e.g. “my_package.my_subpackage”, or list of strings for the names of the modules to be externed. This can also be a glob-style pattern, as described in
mock().exclude (list[str] | str) – An optional pattern that excludes some patterns that match the include string.
allow_empty (bool) – An optional flag that specifies whether the intern modules specified by this call to the
internmethod must be matched to some module during packaging. If aninternmodule glob pattern is added withallow_empty=False, andclose()is called (either explicitly or via__exit__) before any modules match that pattern, an exception is thrown. Ifallow_empty=True, no such exception is thrown.
- interned_modules() list[str][source]
Return all modules that are currently interned.
- Returns:
A list containing the names of modules which will be interned in this package.
- mock(include: str | Iterable[str], *, exclude: str | Iterable[str] = (), allow_empty: bool = True)[source]
Replace some required modules with a mock implementation. Mocked modules will return a fake object for any attribute accessed from it. Because we copy file-by-file, the dependency resolution will sometimes find files that are imported by model files but whose functionality is never used (e.g. custom serialization code or training helpers). Use this function to mock this functionality out without having to modify the original code.
- Parameters:
A string e.g.
"my_package.my_subpackage", or list of strings for the names of the modules to be mocked out. Strings can also be a glob-style pattern string that may match multiple modules. Any required dependencies that match this pattern string will be mocked out automatically.- Examples :
'tensorplay.**'– matchestensorplayand all submodules of tensorplay, e.g.'tensorplay.nn'and'tensorplay.nn.functional''tensorplay.*'– matches'tensorplay.nn'or'tensorplay.functional', but not'tensorplay.nn.functional'
exclude (list[str] | str) – An optional pattern that excludes some patterns that match the include string. e.g.
include='tensorplay.**', exclude='tensorplay.foo'will mock all tensorplay packages except'tensorplay.foo', Default: is[].allow_empty (bool) – An optional flag that specifies whether the mock implementation(s) specified by this call to the
mock()method must be matched to some module during packaging. If a mock is added withallow_empty=False, andclose()is called (either explicitly or via__exit__) and the mock has not been matched to a module used by the package being exported, an exception is thrown. Ifallow_empty=True, no such exception is thrown.
- mocked_modules() list[str][source]
Return all modules that are currently mocked.
- Returns:
A list containing the names of modules which will be mocked in this package.
- register_extern_hook(hook: Callable[[PackageExporter, str], None]) RemovableHandle[source]
Registers an extern hook on the exporter.
The hook will be called each time a module matches against an
extern()pattern. It should have the following signature:hook(exporter: PackageExporter, module_name: str) -> NoneHooks will be called in order of registration.
- Returns:
A handle that can be used to remove the added hook by calling
handle.remove().- Return type:
tensorplay.utils.hooks.RemovableHandle
- register_intern_hook(hook: Callable[[PackageExporter, str], None]) RemovableHandle[source]
Registers an intern hook on the exporter.
The hook will be called each time a module matches against an
intern()pattern. It should have the following signature:hook(exporter: PackageExporter, module_name: str) -> NoneHooks will be called in order of registration.
- Returns:
A handle that can be used to remove the added hook by calling
handle.remove().- Return type:
tensorplay.utils.hooks.RemovableHandle
- register_mock_hook(hook: Callable[[PackageExporter, str], None]) RemovableHandle[source]
Registers a mock hook on the exporter.
The hook will be called each time a module matches against a
mock()pattern. It should have the following signature:hook(exporter: PackageExporter, module_name: str) -> NoneHooks will be called in order of registration.
- Returns:
A handle that can be used to remove the added hook by calling
handle.remove().- Return type:
tensorplay.utils.hooks.RemovableHandle
- save_module(module_name: str, dependencies=True)[source]
Save the code for
moduleinto the package. Code for the module is resolved using theimporterspath to find the module object, and then using its__file__attribute to find the source code.
- save_pickle(package: str, resource: str, obj: Any, dependencies: bool = True, pickle_protocol: int = 3)[source]
Save a python object to the archive using pickle. Equivalent to
tensorplay.save()but saving into the archive rather than a stand-alone file. Standard pickle does not save the code, only the objects. Ifdependenciesis true, this method will also scan the pickled objects for which modules are required to reconstruct them and save the relevant code.To be able to save an object where
type(obj).__name__ismy_module.MyObject,my_module.MyObjectmust resolve to the class of the object according to theimporterorder. When saving objects that have previously been packaged, the importer’simport_modulemethod will need to be present in theimporterlist for this to work.Tensors inside
objare serialized by tensorplay’s own pickling support.- Parameters:
package (str) – The name of module package this resource should go in (e.g.
"my_package.my_subpackage").resource (str) – A unique name for the resource, used to identify it to load.
obj (Any) – The object to save, must be picklable.
dependencies (bool, optional) – If
True, we scan the source for dependencies.
- save_source_file(module_name: str, file_or_directory: str, dependencies=True)[source]
Adds the local file system
file_or_directoryto the source package to provide the code formodule_name.- Parameters:
module_name (str) – e.g.
"my_package.my_subpackage", code will be saved to provide code for this package.file_or_directory (str) – the path to a file or directory of code. When a directory, all python files in the directory are recursively copied using
save_source_file(). If a file is named"/__init__.py"the code is treated as a package.dependencies (bool, optional) – If
True, we scan the source for dependencies.
- save_source_string(module_name: str, src: str, is_package: bool = False, dependencies: bool = True)[source]
Adds
srcas the source code formodule_namein the exported package.- Parameters:
module_name (str) – e.g.
my_package.my_subpackage, code will be saved to provide code for this package.src (str) – The Python source code to save for this package.
is_package (bool, optional) – If
True, this module is treated as a package. Packages are allowed to have submodules (e.g.my_package.my_subpackage.my_subsubpackage), and resources can be saved inside them. Defaults toFalse.dependencies (bool, optional) – If
True, we scan the source for dependencies.
PackageImporter
classFull reference ↗- class tensorplay.package.PackageImporter(file_or_buffer: str | ~os.PathLike[str] | ~typing.IO[bytes] | ~tensorplay.package._archive.PackageFileReader, module_allowed: ~collections.abc.Callable[[str], bool] = <function PackageImporter.<lambda>>)[source]
Importers allow you to load code written to packages by
PackageExporter. Code is loaded in a hermetic way, using files from the package rather than the normal python import system. This allows for the packaging of model code and data so that it can be run on a server or used in the future for transfer learning.The importer for packages ensures that code in the module can only be loaded from within the package, except for modules explicitly listed as external during export. The file
extern_modulesin the zip archive lists all the modules that a package externally depends on. This prevents “implicit” dependencies where the package runs locally because it is importing a locally-installed package, but then fails when the package is copied to another machine.- file_structure(*, include: GlobPattern = '**', exclude: GlobPattern = ()) Directory[source]
Returns a file structure representation of package’s zipfile.
- Parameters:
include (list[str] | str) – An optional string e.g.
"my_package.my_subpackage", or optional list of strings for the names of the files to be included in the zipfile representation. This can also be a glob-style pattern, as described inPackageExporter.mock()exclude (list[str] | str) – An optional pattern that excludes files whose name match the pattern.
- Returns:
- get_name(obj: Any, name: str | None = None) tuple[str, str]
Given an object, return a name that can be used to retrieve the object from this environment.
- Parameters:
obj – An object to get the module-environment-relative name for.
name – If set, use this name instead of looking up
__name__or__qualname__onobj. This is only here to match how Pickler handles__reduce__functions that return a string, don’t use otherwise.
- Returns:
A tuple (parent_module_name, attr_name) that can be used to retrieve
objfrom this environment. To use it:mod = importer.import_module(parent_module_name) obj = getattr(mod, attr_name)- Raises:
ObjNotFoundError – we couldn’t retrieve
objby name.ObjMisMatchError – we found a different object with the same name as
obj.
- id()[source]
Returns internal identifier that tensorplay.package uses to distinguish
PackageImporterinstances. Looks like:<tensorplay_package_0>
- import_module(name: str, package=None)[source]
Load a module from the package if it hasn’t already been loaded, and then return the module. Modules are loaded locally to the importer and will appear in
self.modulesrather thansys.modules.- Parameters:
- Returns:
The (possibly already) loaded module.
- Return type:
- load_pickle(package: str, resource: str, map_location=None) Any[source]
Unpickles the resource from the package, loading any modules that are needed to construct the objects using
import_module().- Parameters:
package (str) – The name of module package (e.g.
"my_package.my_subpackage").resource (str) – The unique name for the resource.
map_location – Retained for interface compatibility; tensorplay embeds tensor payloads directly in the pickle stream, so no remapping of storage records takes place. Defaults to
None.
- Returns:
The unpickled object.
- Return type:
Any
- load_text(package: str, resource: str, encoding: str = 'utf-8', errors: str = 'strict') str[source]
Load a string.
- Parameters:
- Returns:
The loaded text.
- Return type:
- python_version()[source]
Returns the version of python that was used to create this package.
Note: this function is experimental and not Forward Compatible. The plan is to move this into a lock file later on.
- Returns:
str | Nonea python version e.g. 3.8.9 or None if no version was stored with this package
PackagingErrorReason
classFull reference ↗- class tensorplay.package.PackagingErrorReason(*values)[source]
Listing of different reasons a dependency may fail to package.
This enum is used to provide good error messages when
PackagingErroris raised.
Attributes 1
ModuleType
attributeFull reference ↗- tensorplay.package.ModuleType
alias of
ModuleType
Exceptions 4
EmptyMatchError
exceptionFull reference ↗- exception tensorplay.package.EmptyMatchError[source]
This is an exception that is thrown when a mock or extern is marked as
allow_empty=False, and is not matched with any module during packaging.
ObjMismatchError
exceptionFull reference ↗- exception tensorplay.package.ObjMismatchError[source]
Raised when an importer found a different object with the same name as the user-provided one.
ObjNotFoundError
exceptionFull reference ↗- exception tensorplay.package.ObjNotFoundError[source]
Raised when an importer cannot find an object by searching for its name.
PackagingError
exceptionFull reference ↗- exception tensorplay.package.PackagingError(dependency_graph: DiGraph, debug=False)[source]
This exception is raised when there is an issue with exporting a package.
PackageExporterwill attempt to gather up all the errors and present them to you at once.
Help improve this page
Found an error, an unclear step, or a missing example?

