import json
from pathlib import Path
from typing import Any
import numpy as np
def load_json(path) -> dict[str, Any]:
path = Path(path)
return json.loads(path.read_text())
def save_json(path, data) -> None:
path = Path(path)
return path.write_text(json.dumps(data))
# everthing below is FIXED API. Everything above is just a concept and can be changed!
mydir = MyDir("/tmp/testdir1")
assert mydir.path == Path("/tmp/testdir1")
mydir.config.save({"a": 2, "b": "test"})
config = mydir.config.load()
print(f"Config is saved at {mydir.config.path}")
for i in range(10):
ts_data = np.random.uniform(0, 1, 5)
mydir.ts1.save(ts_data, key=i)
all_ts_keys, all_ts_data = mydir.ts1.load_all(sort_it=False) # returns tuple[list, list]
example_ts_data = mydir.ts1.load(key=8)
dynamic_ts_1 = mydir.new_ts("dynamic_ts_1")
for i in range(20):
ts_data = np.random.uniform(0, 1, 5)
dynamic_ts_1.save(ts_data, key=i)
dynamic_ts_1_mean = np.mean(dynamic_ts_1.load_all(sort_it=False), axis=0)
rel_path means relative to the root of MyDir.
Should support autocomplete, type checking, etc. That means that I want for example mydir.conf to be autocompleted to mydir.config. It has to know that there is the member config to do that. A counter-example is a pandas dataframe. I can do df.test123 when there is the column test123, but it won't be suggested for autocomplete since it does not know that there is this member. Similarly, I want type checking to work such that I know the type of config when I do config = mydir.config.load().
Idea of how to declare the directoy, because I don't have the python code yet in which it should be declared to make type support possible:. The Python code should look nothing like this, this just shows what kind of stuff should be declared.
To implement the concept you've described while ensuring autocomplete, type checking, and minimal code duplication, we'll follow a structured approach. The solution involves:
Defining Manager Classes: Create generic manager classes (JSONManager, NumpyManager, TSManager) that handle loading and saving data.
Creating a Base Directory Class: Develop a base BaseDir class that initializes these managers based on a declarative JSON configuration.
Generating Specific Directory Classes: Use the JSON configuration to dynamically generate specific directory classes (MyDir1, MyDir2, etc.) with proper type annotations for autocomplete and type checking.
Using the Directory Classes: Instantiate and use these classes as per your example.
This approach ensures that each directory structure is well-defined, type-safe, and supports IDE features like autocomplete.
Let's dive into the implementation.
1. Manager Classes
These classes encapsulate the logic for loading and saving different types of data.
import numpy as np
from pathlib import Path
from typing import Any
class NumpyManager:
def __init__(self, root: Path, rel_path: str):
self.path: Path = root / rel_path
def load(self) -> np.ndarray:
return np.load(self.path, allow_pickle=True)
def save(self, data: np.ndarray) -> None:
np.save(self.path, data)
c. TSManager
Handles time-series data with dynamic keys.
python
import numpy as np
from pathlib import Path
from typing import Any, List, Tuple
class TSManager:
def __init__(self, root: Path, rel_path: str, file_template: str):
self.dir: Path = root / rel_path
self.dir.mkdir(parents=True, exist_ok=True)
self.file_template = file_template
def save(self, data: np.ndarray, key: Any) -> None:
file_path = self.dir / self.file_template.format(key=key)
np.save(file_path, data)
def load(self, key: Any) -> np.ndarray:
file_path = self.dir / self.file_template.format(key=key)
return np.load(file_path, allow_pickle=True)
def load_all(self, sort_it: bool = False) -> Tuple[List[Any], List[np.ndarray]]:
files = sorted(self.dir.glob("*.npy")) if sort_it else self.dir.glob("*.npy")
keys = []
data = []
for file in files:
# Extract key from filename based on template
name = file.stem
key_part = name.replace(self.file_template.replace("{key}", "").rstrip("_"), "")
keys.append(key_part)
data.append(np.load(file, allow_pickle=True))
return keys, data
2. Base Directory Class
The BaseDir class initializes the managers based on a provided configuration.
python
from pathlib import Path
from typing import Dict, Any
class BaseDir:
def __init__(self, root: Path, config: Dict[str, Any]):
self.root = root
for name, cfg in config.items():
load_fun = cfg.get("load_fun")
save_fun = cfg.get("save_fun")
rel_path = cfg.get("rel_path")
file_template = cfg.get("file_template", None)
if load_fun == "load_json" and save_fun == "save_json":
setattr(self, name, JSONManager(root, rel_path))
elif load_fun == "np.load" and save_fun == "np.save" and file_template is None:
setattr(self, name, NumpyManager(root, rel_path))
elif load_fun == "np.load" and save_fun == "np.save" and file_template is not None:
setattr(self, name, TSManager(root, rel_path, file_template))
else:
raise ValueError(f"Unsupported configuration for {name}")
3. Generating Specific Directory Classes
To achieve autocomplete and type checking, we'll generate specific directory classes with explicit attributes based on the JSON configuration. This can be done manually or via a code generation script. For simplicity, we'll demonstrate manual class creation based on your example.
a. Define the Configuration
First, define the JSON configuration in Python (you can load it from a JSON file if preferred).
Here, we'll manually create classes MyDir1 and MyDir2 using the BaseDir.
python
from typing import Any
class MyDir1(BaseDir):
config: JSONManager
data: NumpyManager
ts1: TSManager
def __init__(self, root: Path = Path("/tmp/testdir1")):
super().__init__(root, CONFIG["MyDir1"])
class MyDir2(BaseDir):
metadata: JSONManager
data: NumpyManager
testts: TSManager
testts2: TSManager
def __init__(self, root: Path = Path("/tmp/testdir2")):
super().__init__(root, CONFIG["MyDir2"])
Explanation:
Explicit Type Annotations: By declaring each attribute with its specific type (JSONManager, NumpyManager, TSManager), IDEs can provide autocomplete and type checking.
Initialization: Each class calls the BaseDir initializer with its specific configuration, setting up the appropriate managers.
c. (Optional) Automate Class Generation
For larger configurations, manual class creation can be tedious. You can automate this using a class factory. However, note that dynamically created classes may not always play well with IDEs for autocomplete. Here's an example using a factory:
python
from typing import Type
def create_dir_class(name: str, config: Dict[str, Any], default_root: Path = Path("/tmp")) -> Type[BaseDir]:
attrs = {}
for member_name, cfg in config.items():
load_fun = cfg.get("load_fun")
save_fun = cfg.get("save_fun")
rel_path = cfg.get("rel_path")
file_template = cfg.get("file_template", None)
if load_fun == "load_json" and save_fun == "save_json":
attrs[member_name] = JSONManager
elif load_fun == "np.load" and save_fun == "np.save" and file_template is None:
attrs[member_name] = NumpyManager
elif load_fun == "np.load" and save_fun == "np.save" and file_template is not None:
attrs[member_name] = TSManager
else:
raise ValueError(f"Unsupported configuration for {member_name}")
# Create the class
return type(
name,
(BaseDir,),
{
"__annotations__": {k: v for k, v in attrs.items()},
"__init__": lambda self, root=default_root: BaseDir.__init__(self, root, config),
}
)
# Example Usage:
MyDir1 = create_dir_class("MyDir1", CONFIG["MyDir1"], Path("/tmp/testdir1"))
MyDir2 = create_dir_class("MyDir2", CONFIG["MyDir2"], Path("/tmp/testdir2"))
Note: While this factory approach reduces manual code, IDEs might not recognize the dynamically created classes for autocomplete and type checking. Therefore, for IDE support, manually defining classes as shown earlier is recommended.
4. Using the Directory Classes
Here's how you can use the MyDir1 and MyDir2 classes with autocomplete and type checking support.
python
from pathlib import Path
import numpy as np
# Initialize the directory
mydir = MyDir1(Path("/tmp/testdir1"))
# Using the config manager
mydir.config.save({"a": 2, "b": "test"})
config = mydir.config.load()
print(f"Config is saved at {mydir.config.path}")
# Using the ts1 manager
for i in range(10):
ts_data = np.random.uniform(0, 1, 5)
mydir.ts1.save(ts_data, key=i)
all_ts_keys, all_ts_data = mydir.ts1.load_all(sort_it=False) # returns tuple[list, list]
example_ts_data = mydir.ts1.load(key=8)
# Creating a new TS manager dynamically
# (Note: For type checking, it's better to define all possible TS managers in the class)
# Here, we'll assume 'dynamic_ts_1' was part of the configuration
# Since it's not, we'll skip type-safe dynamic creation
# Instead, consider adding it to the configuration and regenerating the class
# If 'dynamic_ts_1' is predefined:
# dynamic_ts_1: TSManager
# For demonstration, here's how you might manually add it
mydir.dynamic_ts_1 = TSManager(mydir.root / "dynamic_ts_1", "dynamic_ts_1/", "dynamic_ts_1data_{key}.npy")
for i in range(20):
ts_data = np.random.uniform(0, 1, 5)
mydir.dynamic_ts_1.save(ts_data, key=i)
dynamic_ts_1_mean = np.mean(np.stack([data for data in mydir.dynamic_ts_1.load_all(sort_it=False)[1]]), axis=0)
print(f"Mean of dynamic_ts_1: {dynamic_ts_1_mean}")
Benefits:
Autocomplete: When you type mydir., your IDE will suggest config, data, ts1, etc., with correct method signatures.
Type Checking: Methods like load and save will have correct type annotations, allowing static type checkers like mypy to validate your code.
5. Complete Implementation Example
Putting it all together, here's a complete example.
# main.py
from pathlib import Path
import numpy as np
from directories import MyDir1
def main():
# Initialize the directory
mydir = MyDir1(Path("/tmp/testdir1"))
# Using the config manager
mydir.config.save({"a": 2, "b": "test"})
config = mydir.config.load()
print(f"Config is saved at {mydir.config.path}")
# Using the ts1 manager
for i in range(10):
ts_data = np.random.uniform(0, 1, 5)
mydir.ts1.save(ts_data, key=i)
all_ts_keys, all_ts_data = mydir.ts1.load_all(sort_it=False) # returns tuple[list, list]
example_ts_data = mydir.ts1.load(key=8)
print(f"Loaded ts1 data for key 8: {example_ts_data}")
# Calculating mean for ts1 data
ts_stack = np.stack(all_ts_data)
ts_mean = np.mean(ts_stack, axis=0)
print(f"Mean of ts1 data: {ts_mean}")
if __name__ == "__main__":
main()
6. Advantages of This Approach
Autocomplete and Type Checking: By explicitly defining class attributes with type annotations, IDEs like VSCode or PyCharm can provide autocomplete suggestions and static type checking.
Modularity: Manager classes are modular and can be reused across different directory structures.
Scalability: Adding new directory structures (MyDir3, etc.) requires minimal effort by creating new classes with their configurations.
KISS Principle: The design is simple, easy to understand, and adheres to the "Keep It Simple, Stupid" principle.
Minimal Code Duplication: By leveraging inheritance and generic manager classes, redundant code is minimized.
7. Notes and Considerations
Dynamic TS Managers: If you need to create TS managers dynamically (i.e., not predefined in the configuration), you'll lose type checking and autocomplete for those instances. To maintain type safety, it's recommended to define all necessary managers in the configuration and corresponding classes.
Error Handling: The provided implementation includes basic error handling for unsupported configurations. Depending on your needs, you might want to enhance this with more detailed exceptions or logging.
Configuration Source: While the example uses a Python dictionary for configuration, you can easily adapt it to load from a JSON file using the load_json function.
Code Generation: For very large and dynamic configurations, consider implementing a code generation script that reads the JSON configuration and automatically generates the corresponding Python classes with type annotations.
This implementation should fulfill your requirements by providing a fixed API with support for autocomplete and type checking, all while maintaining simplicity and reducing code duplication. Feel free to expand and adapt this structure to fit more complex scenarios as needed.