pkl-python 0.0.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Jungwoo Yang
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,168 @@
1
+ Metadata-Version: 2.1
2
+ Name: pkl-python
3
+ Version: 0.0.0
4
+ Summary: Python library for Apple's PKL.
5
+ Author-email: Jungwoo Yang <jwyang0213@gmail.com>
6
+ License: MIT License
7
+
8
+ Copyright (c) 2024 Jungwoo Yang
9
+
10
+ Permission is hereby granted, free of charge, to any person obtaining a copy
11
+ of this software and associated documentation files (the "Software"), to deal
12
+ in the Software without restriction, including without limitation the rights
13
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14
+ copies of the Software, and to permit persons to whom the Software is
15
+ furnished to do so, subject to the following conditions:
16
+
17
+ The above copyright notice and this permission notice shall be included in all
18
+ copies or substantial portions of the Software.
19
+
20
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
26
+ SOFTWARE.
27
+
28
+ Project-URL: Homepage, https://github.com/jw-y/pkl
29
+ Project-URL: Bug Reports, https://github.com/jw-y/pkl/issues
30
+ Project-URL: Source, https://github.com/jw-y/pkl
31
+ Classifier: Programming Language :: Python :: 3
32
+ Classifier: License :: OSI Approved :: MIT License
33
+ Classifier: Operating System :: OS Independent
34
+ Requires-Python: >=3.7
35
+ Description-Content-Type: text/markdown
36
+ License-File: LICENSE
37
+ Requires-Dist: msgpack>=1.0.8
38
+ Provides-Extra: dev
39
+ Requires-Dist: pre-commit; extra == "dev"
40
+ Requires-Dist: black; extra == "dev"
41
+ Requires-Dist: isort; extra == "dev"
42
+ Requires-Dist: mypy; extra == "dev"
43
+ Requires-Dist: pylint; extra == "dev"
44
+ Requires-Dist: pytest; extra == "dev"
45
+ Requires-Dist: pytest-cov; extra == "dev"
46
+ Requires-Dist: tox; extra == "dev"
47
+
48
+ > [!CAUTION]
49
+ >
50
+ > # THIS LIBRARY IS CURRENTLY PRE-RELEASE
51
+ >
52
+ > `pkl-python` is currently major version `v0`, and **breaking changes will happen** between versions.
53
+
54
+ # pkl-python - Pkl Bindings for Python
55
+ Python binding for [Apple's Pkl language](https://pkl-lang.org/index.html).
56
+
57
+ ## Getting Started
58
+ ### Installation
59
+
60
+ ``` bash
61
+ pip install pkl-python
62
+ ```
63
+
64
+ ### Basic Usage
65
+ Here's how you can start using `pkl-python` to load a PKL module:
66
+
67
+ ```python
68
+ import pkl
69
+
70
+ config = pkl.load("path/to/pkl/example_module.pkl")
71
+ print(config)
72
+ ```
73
+
74
+ ### Status
75
+ * Evaluator API: fully functional
76
+ * Code Generation: in development
77
+
78
+ ### TODO
79
+ * [x] (codgen) fix class order
80
+ * [ ] (codgen) pip binary installation
81
+ * [ ] (codgen) clean up code
82
+
83
+
84
+ ## Usage
85
+
86
+ ## Advanced Features
87
+ For details on the parameters, refer [Message Passing API](https://pkl-lang.org/main/current/bindings-specification/message-passing-api.html).
88
+
89
+ ```python
90
+ import pkl
91
+
92
+ config = pkl.load("./tests/types.pkl")
93
+ config = pkl.load("./tests/types.pkl", expr="datasize")
94
+ config = pkl.load(None, module_text="a: Int = 1 + 1")
95
+ config = pkl.load("./tests/types.pkl", debug=True)
96
+ ```
97
+
98
+ ### Custom Readers
99
+ It is possible to add module or resource or module readers:
100
+ ```python
101
+ from typing import List
102
+ from dataclasses import dataclass
103
+
104
+ import pkl
105
+ from pkl import (
106
+ ModuleReader, ResourceReader, PathElement,
107
+ ModuleSource, PreconfiguredOptions, PklError,
108
+ )
109
+
110
+ class TestModuleReader(ModuleReader):
111
+ def read(self, url) -> str:
112
+ return "foo = 1"
113
+
114
+ def list_elements(self, url: str) -> List[PathElement]:
115
+ return [PathElement("foo.pkl", False)]
116
+
117
+ opts = PreconfiguredOptions(
118
+ moduleReaders=[TestModuleReader("customfs", True, True, True)]
119
+ )
120
+ opts.allowedModules.append("customfs:")
121
+ config = pkl.load("./tests/myModule.pkl", evaluator_options=opts)
122
+ ```
123
+
124
+ ## Appendix
125
+
126
+ ### Type Mappings
127
+
128
+ While in pre-release they are subject to change.
129
+
130
+ | Pkl type | TypeScript type |
131
+ | ---------------- | -------------------------- |
132
+ | Null | `None` |
133
+ | Boolean | `bool` |
134
+ | String | `str` |
135
+ | Int | `int` |
136
+ | Int8 | `int` |
137
+ | Int16 | `int` |
138
+ | Int32 | `int` |
139
+ | UInt | `int` |
140
+ | UInt8 | `int` |
141
+ | UInt16 | `int` |
142
+ | UInt32 | `int` |
143
+ | Float | `float` |
144
+ | Number | `float` |
145
+ | List | `list` |
146
+ | Listing | `list` |
147
+ | Map | `dict` |
148
+ | Mapping | `dict` |
149
+ | Set | `set` |
150
+ | Pair | `pkl.Pair` |
151
+ | Dynamic | `dataclasses.dataclass` |
152
+ | DataSize | `pkl.DataSize` |
153
+ | Duration | `pkl.Duration` |
154
+ | IntSeq | `pkl.IntSeq` |
155
+ | Class | `dataclasses.dataclass` |
156
+ | TypeAlias | `typing` |
157
+ | Any | `typing.Any` |
158
+ | Unions (A\|B\|C) | `typing.Union[A\|B\|C]` |
159
+ | Regex | `pkl.Regex` |
160
+
161
+ ## Contributing
162
+ Contributions are welcome! If you'd like to contribute, please fork the repository and submit a pull request. For major changes, please open an issue first to discuss what you would like to change.
163
+
164
+ ## License
165
+ PKL is released under the MIT License. See the LICENSE file for more details.
166
+
167
+ ## Contact
168
+ For support or to contribute, please contact jwyang0213@gmail.com or visit our GitHub repository to report issues or submit pull requests.
@@ -0,0 +1,121 @@
1
+ > [!CAUTION]
2
+ >
3
+ > # THIS LIBRARY IS CURRENTLY PRE-RELEASE
4
+ >
5
+ > `pkl-python` is currently major version `v0`, and **breaking changes will happen** between versions.
6
+
7
+ # pkl-python - Pkl Bindings for Python
8
+ Python binding for [Apple's Pkl language](https://pkl-lang.org/index.html).
9
+
10
+ ## Getting Started
11
+ ### Installation
12
+
13
+ ``` bash
14
+ pip install pkl-python
15
+ ```
16
+
17
+ ### Basic Usage
18
+ Here's how you can start using `pkl-python` to load a PKL module:
19
+
20
+ ```python
21
+ import pkl
22
+
23
+ config = pkl.load("path/to/pkl/example_module.pkl")
24
+ print(config)
25
+ ```
26
+
27
+ ### Status
28
+ * Evaluator API: fully functional
29
+ * Code Generation: in development
30
+
31
+ ### TODO
32
+ * [x] (codgen) fix class order
33
+ * [ ] (codgen) pip binary installation
34
+ * [ ] (codgen) clean up code
35
+
36
+
37
+ ## Usage
38
+
39
+ ## Advanced Features
40
+ For details on the parameters, refer [Message Passing API](https://pkl-lang.org/main/current/bindings-specification/message-passing-api.html).
41
+
42
+ ```python
43
+ import pkl
44
+
45
+ config = pkl.load("./tests/types.pkl")
46
+ config = pkl.load("./tests/types.pkl", expr="datasize")
47
+ config = pkl.load(None, module_text="a: Int = 1 + 1")
48
+ config = pkl.load("./tests/types.pkl", debug=True)
49
+ ```
50
+
51
+ ### Custom Readers
52
+ It is possible to add module or resource or module readers:
53
+ ```python
54
+ from typing import List
55
+ from dataclasses import dataclass
56
+
57
+ import pkl
58
+ from pkl import (
59
+ ModuleReader, ResourceReader, PathElement,
60
+ ModuleSource, PreconfiguredOptions, PklError,
61
+ )
62
+
63
+ class TestModuleReader(ModuleReader):
64
+ def read(self, url) -> str:
65
+ return "foo = 1"
66
+
67
+ def list_elements(self, url: str) -> List[PathElement]:
68
+ return [PathElement("foo.pkl", False)]
69
+
70
+ opts = PreconfiguredOptions(
71
+ moduleReaders=[TestModuleReader("customfs", True, True, True)]
72
+ )
73
+ opts.allowedModules.append("customfs:")
74
+ config = pkl.load("./tests/myModule.pkl", evaluator_options=opts)
75
+ ```
76
+
77
+ ## Appendix
78
+
79
+ ### Type Mappings
80
+
81
+ While in pre-release they are subject to change.
82
+
83
+ | Pkl type | TypeScript type |
84
+ | ---------------- | -------------------------- |
85
+ | Null | `None` |
86
+ | Boolean | `bool` |
87
+ | String | `str` |
88
+ | Int | `int` |
89
+ | Int8 | `int` |
90
+ | Int16 | `int` |
91
+ | Int32 | `int` |
92
+ | UInt | `int` |
93
+ | UInt8 | `int` |
94
+ | UInt16 | `int` |
95
+ | UInt32 | `int` |
96
+ | Float | `float` |
97
+ | Number | `float` |
98
+ | List | `list` |
99
+ | Listing | `list` |
100
+ | Map | `dict` |
101
+ | Mapping | `dict` |
102
+ | Set | `set` |
103
+ | Pair | `pkl.Pair` |
104
+ | Dynamic | `dataclasses.dataclass` |
105
+ | DataSize | `pkl.DataSize` |
106
+ | Duration | `pkl.Duration` |
107
+ | IntSeq | `pkl.IntSeq` |
108
+ | Class | `dataclasses.dataclass` |
109
+ | TypeAlias | `typing` |
110
+ | Any | `typing.Any` |
111
+ | Unions (A\|B\|C) | `typing.Union[A\|B\|C]` |
112
+ | Regex | `pkl.Regex` |
113
+
114
+ ## Contributing
115
+ Contributions are welcome! If you'd like to contribute, please fork the repository and submit a pull request. For major changes, please open an issue first to discuss what you would like to change.
116
+
117
+ ## License
118
+ PKL is released under the MIT License. See the LICENSE file for more details.
119
+
120
+ ## Contact
121
+ For support or to contribute, please contact jwyang0213@gmail.com or visit our GitHub repository to report issues or submit pull requests.
@@ -0,0 +1,67 @@
1
+ [build-system]
2
+ requires = ["setuptools>=42", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "pkl-python"
7
+ dynamic = ["version"]
8
+ description = "Python library for Apple's PKL."
9
+ authors = [
10
+ { name = "Jungwoo Yang", email = "jwyang0213@gmail.com" },
11
+ ]
12
+ license = { file = "LICENSE" }
13
+ readme = "README.md"
14
+ requires-python = ">=3.7"
15
+ classifiers = [
16
+ "Programming Language :: Python :: 3",
17
+ "License :: OSI Approved :: MIT License",
18
+ "Operating System :: OS Independent",
19
+ ]
20
+ dependencies = [
21
+ "msgpack >= 1.0.8",
22
+ ]
23
+
24
+ [tool.setuptools.packages.find]
25
+ where = ["src"]
26
+ #include = ["pkl", "pkl_gen_python.py"]
27
+
28
+ [tool.setuptools.dynamic]
29
+ version = {file = "pkl/VERSION"}
30
+
31
+ [project.optional-dependencies]
32
+ dev = [
33
+ "pre-commit",
34
+ "black",
35
+ "isort",
36
+ "mypy",
37
+ "pylint",
38
+ "pytest",
39
+ "pytest-cov",
40
+ "tox",
41
+ ]
42
+
43
+ [project.urls]
44
+ "Homepage" = "https://github.com/jw-y/pkl"
45
+ "Bug Reports" = "https://github.com/jw-y/pkl/issues"
46
+ "Source" = "https://github.com/jw-y/pkl"
47
+
48
+ [project.scripts]
49
+ pkl-gen-python = "pkl_gen_python:main"
50
+
51
+ [tool.twine]
52
+ repository = "pypi"
53
+
54
+ [tool.black]
55
+ line-length = 88
56
+ target-version = ['py310']
57
+ force-exclude = 'codegen/snippet-tests/output/'
58
+
59
+ [tool.isort]
60
+ profile = "black"
61
+ skip = ["codegen/snippet-tests/output/*"]
62
+
63
+ [tool.autoflake]
64
+ exclude = ["codegen/snippet-tests/output/*"]
65
+
66
+ [tool.pytest.ini_options]
67
+ addopts = "-ra -q"
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,74 @@
1
+ import os
2
+ import platform
3
+ import stat
4
+ from pathlib import Path
5
+
6
+ import setuptools
7
+ from setuptools.command.install import install
8
+
9
+ BINARIES = {
10
+ ("darwin", "64bit"): "pkl-macos-amd64",
11
+ ("darwin", "aarch64"): "pkl-macos-aarch64",
12
+ ("linux", "64bit"): "pkl-linux-amd64",
13
+ ("linux", "aarch64"): "pkl-linux-aarch64",
14
+ ("linux", "64bit", "alpine"): "pkl-alpine-linux-amd64",
15
+ }
16
+ PKL_VERSION = "0.25.3"
17
+ BASE_PATH = "https://github.com/apple/pkl/releases/download/"
18
+
19
+
20
+ def detect_system():
21
+ os_name = platform.system().lower()
22
+ arch, _ = platform.architecture()
23
+ return os_name, arch
24
+
25
+
26
+ def is_alpine_linux():
27
+ return os.path.isfile("/etc/alpine-release")
28
+
29
+
30
+ def download_binary(file, target_fp):
31
+ import requests
32
+
33
+ url = BASE_PATH + PKL_VERSION + "/" + file
34
+ response = requests.get(url)
35
+ with open(target_fp, "wb") as f:
36
+ f.write(response.content)
37
+
38
+
39
+ def get_binary_path():
40
+ os_name, arch = detect_system()
41
+ if os_name == "linux" and is_alpine_linux():
42
+ os_name = "alpine"
43
+ binary_key = (os_name, arch)
44
+ if binary_key == ("linux", "64bit") and is_alpine_linux():
45
+ binary_key += ("alpine",)
46
+ bin_file = BINARIES.get(binary_key)
47
+
48
+ if bin_file is None:
49
+ raise OSError("No compatible binary found for your system.")
50
+
51
+ bin_parent_path = (Path("~/.pkl/bin/") / PKL_VERSION).expanduser()
52
+ binary_path = bin_parent_path / bin_file
53
+
54
+ if not binary_path.exists():
55
+ binary_path.parent.mkdir(exist_ok=True, parents=True)
56
+ download_binary(bin_file, binary_path)
57
+
58
+ current_permissions = os.stat(binary_path).st_mode
59
+ new_permissions = current_permissions | stat.S_IXUSR
60
+ os.chmod(binary_path, new_permissions)
61
+
62
+ return binary_path
63
+
64
+
65
+ class CustomInstallCommand(install):
66
+ def run(self):
67
+ get_binary_path()
68
+ install.run(self)
69
+
70
+
71
+ setuptools.setup(
72
+ cmdclass={"install": CustomInstallCommand},
73
+ setup_requires=["requests"],
74
+ )
@@ -0,0 +1,118 @@
1
+ import os
2
+ from pathlib import Path
3
+ from typing import Optional, Union
4
+ from urllib.parse import ParseResult, urlparse
5
+
6
+ from pkl.evaluator_manager import Evaluator, EvaluatorManager
7
+ from pkl.evaluator_options import EvaluatorOptions, PreconfiguredOptions
8
+ from pkl.parser import DataSize, Duration, IntSeq, Pair, Parser, Regex
9
+ from pkl.reader import ModuleReader, PathElement, ResourceReader
10
+ from pkl.utils import ModuleSource, PklBugError, PklError
11
+
12
+ # get version
13
+ with open(os.path.join(os.path.dirname(__file__), "VERSION"), "r") as _f:
14
+ __version__ = _f.read().strip()
15
+
16
+
17
+ class PklDefaultType:
18
+ def __repr__(self):
19
+ return "<PklDefault>"
20
+
21
+
22
+ PKL_DEFAULT = PklDefaultType()
23
+
24
+
25
+ def _search_project_dir(module_path: str) -> str:
26
+ cur_path = Path(module_path).parent.absolute()
27
+ while not (cur_path / "PklProject").exists():
28
+ cur_path = cur_path.parent
29
+ if str(cur_path) == "/":
30
+ break
31
+
32
+ if str(cur_path) == "/":
33
+ cur_path = Path(module_path).parent
34
+ return str(cur_path.absolute())
35
+
36
+
37
+ def load(
38
+ module_uri: Union[str, Path],
39
+ *,
40
+ module_text: Optional[str] = None,
41
+ expr: Optional[str] = None,
42
+ project_dir: str = PKL_DEFAULT,
43
+ evaluator_options: EvaluatorOptions = PreconfiguredOptions(),
44
+ parser=None,
45
+ debug=False,
46
+ **kwargs,
47
+ ):
48
+ """
49
+ Loads and evaluates a Pkl module or expression with specified parameters and customization options.
50
+
51
+ Args:
52
+ module_uri (str): The absolute URI of the module to be loaded.
53
+ module_text (Optional[str], None): Optionally, the content of the module to be loaded.
54
+ If None, the module is loaded from the specified URI.
55
+ expr (Optional[str], None): Optionally, a Pkl expression to be evaluated
56
+ within the loaded module. If None, the entire module is evaluated.
57
+ project_dir (str, PKL_DEFAULT): The project directory to use for this command.
58
+ By default, searches up from the working directory for a PklProject file.
59
+ evaluator_options (EvaluatorOptions, PreconfiguredOptions()):
60
+ extra options for evaluator
61
+ parser: A specific parser to be used for parsing the module.
62
+ If None, a default parser is used.
63
+ debug (bool, False): Enable debugging mode for additional output and diagnostics.
64
+ **kwargs: Additional keyword arguments for extensibility and future use.
65
+
66
+ Returns:
67
+ The result of the module or expression evaluation, depending on the inputs and configuration.
68
+
69
+ This function provides a flexible interface for loading and evaluating Pkl modules
70
+ with a variety of customization options, including custom module and resource readers,
71
+ environmental configurations, and support for complex project dependencies.
72
+ """
73
+
74
+ parsed = urlparse(str(module_uri))
75
+
76
+ def is_uri(_uri: ParseResult):
77
+ return bool(_uri.scheme) and (bool(_uri.netloc) or bool(_uri.path))
78
+
79
+ if module_text:
80
+ source = ModuleSource.from_text(module_text)
81
+ elif is_uri(parsed):
82
+ source = ModuleSource.from_uri(module_uri)
83
+ else:
84
+ source = ModuleSource.from_path(module_uri)
85
+
86
+ if project_dir is PKL_DEFAULT:
87
+ project_dir = _search_project_dir(str(module_uri))
88
+
89
+ with EvaluatorManager(debug=debug) as manager:
90
+ if (Path(project_dir) / "PklProject").exists():
91
+ evaluator = manager.new_project_evaluator(
92
+ project_dir, evaluator_options, parser=parser
93
+ )
94
+ else:
95
+ evaluator = manager.new_evaluator(evaluator_options, parser=parser)
96
+ config = evaluator.evaluate_expression(source, expr)
97
+ return config
98
+
99
+
100
+ __all__ = [
101
+ "load",
102
+ "Evaluator",
103
+ "EvaluatorManager",
104
+ "EvaluatorOptions",
105
+ "PreconfiguredOptions",
106
+ "ModuleReader",
107
+ "ResourceReader",
108
+ "PathElement",
109
+ "Parser",
110
+ "ModuleSource",
111
+ "PklError",
112
+ "PklBugError",
113
+ "Duration",
114
+ "DataSize",
115
+ "Pair",
116
+ "IntSeq",
117
+ "Regex",
118
+ ]