runfn 0.1.0__py3-none-any.whl

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.
runfn/__init__.py ADDED
@@ -0,0 +1,8 @@
1
+ """runfn: Run any Python function from the terminal or programmatically."""
2
+
3
+ from runfn.core import load_module, parse_literal, run_fn
4
+
5
+ run = run_fn
6
+
7
+ __version__ = "0.1.0"
8
+ __all__ = ["run", "run_fn", "load_module", "parse_literal", "__version__"]
runfn/cli.py ADDED
@@ -0,0 +1,75 @@
1
+ """CLI entry point for runfn."""
2
+
3
+ from pathlib import Path
4
+ import sys
5
+ import time
6
+ from typing import Any
7
+
8
+ import fire
9
+
10
+ from runfn.core import _MISSING, load_module, parse_literal, run_fn
11
+
12
+
13
+ def run(path: str, func: str, *args: Any, expect: Any = _MISSING, time_it: bool = False, **kwargs: Any) -> None:
14
+ """Run FUNC from the Python file PATH with the given arguments."""
15
+ if func.startswith("_"):
16
+ print(f"Error: Access to private function '{func}' is not allowed")
17
+ sys.exit(2)
18
+
19
+ try:
20
+ mod = load_module(path)
21
+ except FileNotFoundError as e:
22
+ print(f"Error: {e}")
23
+ sys.exit(2)
24
+ except ValueError as e:
25
+ print(f"Error: {e}")
26
+ sys.exit(2)
27
+ except Exception as e:
28
+ print(f"Error loading module {path}: {e}")
29
+ sys.exit(2)
30
+
31
+ if not hasattr(mod, func):
32
+ print(f"Error: '{func}' not found in {path}")
33
+ sys.exit(2)
34
+
35
+ fn = getattr(mod, func)
36
+ if not callable(fn):
37
+ print(f"Error: '{func}' in {path} is not callable")
38
+ sys.exit(2)
39
+
40
+ start = time.perf_counter()
41
+ try:
42
+ result = fn(*args, **kwargs)
43
+ except Exception as e:
44
+ print(f"Error running '{func}': {e}")
45
+ sys.exit(1)
46
+ elapsed = time.perf_counter() - start
47
+
48
+ if result is None:
49
+ print("Result: None (function has no return value)")
50
+ else:
51
+ print(f"Result: {result!r}")
52
+
53
+ failed = False
54
+ if expect is not _MISSING:
55
+ expected = parse_literal(expect)
56
+ if result == expected:
57
+ print("PASS")
58
+ else:
59
+ note = ", but the function returned nothing" if result is None else ""
60
+ print(f"FAIL (expected {expected!r}{note})")
61
+ failed = True
62
+
63
+ if time_it:
64
+ print(f"Time: {elapsed * 1000:.3f} ms")
65
+
66
+ if failed:
67
+ sys.exit(1)
68
+
69
+
70
+ def main() -> None:
71
+ fire.Fire(run)
72
+
73
+
74
+ if __name__ == "__main__":
75
+ main()
runfn/core.py ADDED
@@ -0,0 +1,52 @@
1
+ """Core library functions for running Python functions dynamically."""
2
+
3
+ import ast
4
+ import importlib.util
5
+ from pathlib import Path
6
+ from typing import Any
7
+ import sys
8
+
9
+ _MISSING = object()
10
+
11
+
12
+ def load_module(path: str | Path):
13
+ """Load a Python module from a file path safely."""
14
+ file_path = Path(path).resolve()
15
+ if not file_path.is_file():
16
+ raise FileNotFoundError(f"File not found: {path}")
17
+ if file_path.suffix != ".py":
18
+ raise ValueError(f"Target file must be a Python (.py) file: {path}")
19
+
20
+ spec = importlib.util.spec_from_file_location("target", str(file_path))
21
+ if spec is None or spec.loader is None:
22
+ raise ImportError(f"Cannot load Python file: {path}")
23
+
24
+ mod = importlib.util.module_from_spec(spec)
25
+ spec.loader.exec_module(mod)
26
+ return mod
27
+
28
+
29
+ def run_fn(path: str | Path, func: str, *args: Any, **kwargs: Any) -> Any:
30
+ """Run FUNC from the Python file PATH with the given arguments and return its result."""
31
+ if func.startswith("_"):
32
+ raise PermissionError(f"Access to private function '{func}' is not allowed")
33
+
34
+ mod = load_module(path)
35
+ if not hasattr(mod, func):
36
+ raise AttributeError(f"'{func}' not found in {path}")
37
+
38
+ fn = getattr(mod, func)
39
+ if not callable(fn):
40
+ raise TypeError(f"'{func}' in {path} is not callable")
41
+
42
+ return fn(*args, **kwargs)
43
+
44
+
45
+ def parse_literal(value: Any) -> Any:
46
+ """Safely parse literal expressions using ast.literal_eval."""
47
+ if not isinstance(value, str):
48
+ return value
49
+ try:
50
+ return ast.literal_eval(value)
51
+ except (ValueError, SyntaxError):
52
+ return value
runfn/py.typed ADDED
@@ -0,0 +1 @@
1
+
@@ -0,0 +1,169 @@
1
+ Metadata-Version: 2.5
2
+ Name: runfn
3
+ Version: 0.1.0
4
+ Summary: Run any Python function from the terminal, with expected-output checks and timing
5
+ Project-URL: Homepage, https://github.com/KavyanshSharma09/runfn
6
+ Project-URL: Repository, https://github.com/KavyanshSharma09/runfn
7
+ Project-URL: Issues, https://github.com/KavyanshSharma09/runfn/issues
8
+ Author-email: Kavyansh Sharma <kavyanshsharma2004@gmail.com>
9
+ License: MIT License
10
+
11
+ Copyright (c) 2026 Kavyansh Sharma
12
+
13
+ Permission is hereby granted, free of charge, to any person obtaining a copy
14
+ of this software and associated documentation files (the "Software"), to deal
15
+ in the Software without restriction, including without limitation the rights
16
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
17
+ copies of the Software, and to permit persons to whom the Software is
18
+ furnished to do so, subject to the following conditions:
19
+
20
+ The above copyright notice and this permission notice shall be included in all
21
+ copies or substantial portions of the Software.
22
+
23
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
24
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
26
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
27
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
28
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29
+ SOFTWARE.
30
+ License-File: LICENSE
31
+ Classifier: License :: OSI Approved :: MIT License
32
+ Classifier: Operating System :: OS Independent
33
+ Classifier: Programming Language :: Python :: 3
34
+ Requires-Python: >=3.8
35
+ Requires-Dist: fire
36
+ Provides-Extra: dev
37
+ Requires-Dist: pytest; extra == 'dev'
38
+ Description-Content-Type: text/markdown
39
+
40
+ # runfn
41
+
42
+ Run any function in a Python file straight from the terminal, check its output, and time it. No edits to your code required. Built with [Google Fire](https://github.com/google/python-fire).
43
+
44
+ ---
45
+
46
+ ## Features
47
+
48
+ - **Zero-Boilerplate:** Run any function directly from any `.py` file without writing CLI wrappers or `if __name__ == '__main__':` blocks.
49
+ - **Output Assertions:** Use `--expect=VALUE` to assert expected results (supports literal values like numbers, booleans, lists, dicts, strings, and `None`).
50
+ - **Execution Timing:** Benchmark execution time in milliseconds with `--time_it`.
51
+ - **Built-in Safety:** Prevents invocation of private/internal attributes (`_...`), verifies callables, and checks file extensions.
52
+ - **CI/CD Friendly:** Deterministic exit codes for easy integration into test pipelines and scripts.
53
+
54
+ ---
55
+
56
+ ## Installation
57
+
58
+ ```bash
59
+ pip install runfn
60
+ ```
61
+
62
+ For development and running tests locally:
63
+
64
+ ```bash
65
+ pip install -e ".[dev]"
66
+ ```
67
+
68
+ ---
69
+
70
+ ## Usage
71
+
72
+ ### As a Python Library
73
+
74
+ ```python
75
+ import runfn
76
+
77
+ # Call any function dynamically and get its return value
78
+ result = runfn.run("myfile.py", "add", 2, 5)
79
+ print(result) # 7
80
+
81
+ # With keyword arguments
82
+ greeting = runfn.run("myfile.py", "greet", name="Sam")
83
+ print(greeting) # 'Hello Sam'
84
+ ```
85
+
86
+ ### From the Command Line (CLI)
87
+
88
+ ```bash
89
+ runfn myfile.py add 2 5
90
+ # Output:
91
+ # Result: 7
92
+ ```
93
+
94
+ ### Keyword Arguments
95
+
96
+ ```bash
97
+ runfn myfile.py greet --name=Sam
98
+ # Output:
99
+ # Result: 'Hello Sam'
100
+ ```
101
+
102
+ ### Assertions (`--expect`)
103
+
104
+ Compare the returned value against an expected literal:
105
+
106
+ ```bash
107
+ runfn myfile.py add 2 5 --expect=7
108
+ # Output:
109
+ # Result: 7
110
+ # PASS
111
+
112
+ runfn myfile.py add 2 5 --expect=8
113
+ # Output:
114
+ # Result: 7
115
+ # FAIL (expected 8)
116
+ ```
117
+
118
+ Functions returning `None` can also be checked:
119
+
120
+ ```bash
121
+ runfn myfile.py log_message "Hello" --expect=None
122
+ # PASS
123
+ ```
124
+
125
+ ### Execution Timing (`--time_it`)
126
+
127
+ Measure execution time of your function call:
128
+
129
+ ```bash
130
+ runfn myfile.py add 2 5 --expect=7 --time_it
131
+ # Output:
132
+ # Result: 7
133
+ # PASS
134
+ # Time: 0.042 ms
135
+ ```
136
+
137
+ ---
138
+
139
+ ## Exit Codes
140
+
141
+ | Exit Code | Meaning |
142
+ | :--- | :--- |
143
+ | **0** | Success (function ran and any `--expect` assertion passed). |
144
+ | **1** | Function execution failed or `--expect` assertion failed. |
145
+ | **2** | CLI / Target error (file not found, invalid `.py` extension, function not found, private attribute access, or non-callable). |
146
+
147
+ ---
148
+
149
+ ## Limitations & Safety
150
+
151
+ - Target functions cannot have arguments named `expect` or `time_it`, as these flags are reserved by the runner.
152
+ - Private functions or attributes (names starting with `_`) and non-callable attributes cannot be called.
153
+
154
+ ---
155
+
156
+ ## Running Tests
157
+
158
+ Run the test suite with `pytest`:
159
+
160
+ ```bash
161
+ pytest
162
+ ```
163
+
164
+ ---
165
+
166
+ ## License
167
+
168
+ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
169
+
@@ -0,0 +1,9 @@
1
+ runfn/__init__.py,sha256=_3FVCLywUg4aEvx4ULKYUHSbWyc-WZs_zIwa3iYjMs0,247
2
+ runfn/cli.py,sha256=kETcU3EDPxK4I5kgwMP3q7omVgzzqpy_o2Zn0cOPYQU,1896
3
+ runfn/core.py,sha256=X7V7ax1sJ3bLsCuz110uQtSsadT9RiIQ5eut0TpkCwI,1622
4
+ runfn/py.typed,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1
5
+ runfn-0.1.0.dist-info/METADATA,sha256=-8-Yz2-ORB5BLUYKA-a_yfipLHFEV7FK_X5EcdN5tKc,4742
6
+ runfn-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
7
+ runfn-0.1.0.dist-info/entry_points.txt,sha256=G4SvtEjgAOc9JNOig-m7cXOp14zhjpyn-FQqfmn8tAE,41
8
+ runfn-0.1.0.dist-info/licenses/LICENSE,sha256=A5A8bb3Rgo6mjvGE-a6CvJhMbr28GL4aWzaUM1N_R2o,1072
9
+ runfn-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ runfn = runfn.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Kavyansh Sharma
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.