Source code for irsim.config.path_param
import os
import sys
from dataclasses import dataclass, field
from typing import cast
import irsim
[docs]
def output_root() -> str:
"""Directory the output folders are created under.
The folder of the running script when there is one, otherwise the current
working directory: under ``python -c``, a REPL or a notebook ``sys.path[0]``
is empty, and ``"" + "/figure"`` would point at the filesystem root.
"""
base = sys.path[0] if sys.path else ""
return base if base else os.getcwd()
[docs]
@dataclass
class PathManager:
"""
Module for managing the path of the project.
- root_path: path of the irsim package
- ani_buffer_path: path of the animation buffer
- ani_path: path of the animation
- fig_path: path of the saved figure
The three output paths default to folders under :func:`output_root`.
"""
root_path: str = os.path.dirname(cast(str, irsim.__file__))
ani_buffer_path: str = field(
default_factory=lambda: output_root() + "/animation_buffer"
)
ani_path: str = field(default_factory=lambda: output_root() + "/animation")
fig_path: str = field(default_factory=lambda: output_root() + "/figure")
# Multi-env storage (default index 0)
_instances: list[PathManager] = [PathManager()]
_current = _instances[0]
[docs]
def bind(instance: PathManager) -> None:
"""Bind instance to default index 0 and update current alias."""
global _current
if _instances:
_instances[0] = instance
else:
_instances.append(instance)
_current = instance
class _Proxy:
def __getattr__(self, name: str):
return getattr(_current, name)
def __setattr__(self, name: str, value):
setattr(_current, name, value)
path_manager = _Proxy()
def __getitem__(index: int) -> PathManager:
return _instances[index]
def __setitem__(index: int, instance: PathManager) -> None:
"""Assign a PathManager at a specific index. Extends list if needed."""
global _current
if index < 0:
raise IndexError("path_param index must be non-negative")
if index >= len(_instances):
_instances.extend(PathManager() for _ in range(index - len(_instances) + 1))
_instances[index] = instance
if index == 0:
_current = instance