runfn 0.1.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,51 @@
1
+ name: Publish to PyPI
2
+
3
+ on:
4
+ push:
5
+ branches:
6
+ - main
7
+ tags:
8
+ - "v*"
9
+ release:
10
+ types: [published]
11
+ workflow_dispatch:
12
+
13
+ jobs:
14
+ build:
15
+ name: Build distribution 📦
16
+ runs-on: ubuntu-latest
17
+
18
+ steps:
19
+ - uses: actions/checkout@v4
20
+ - name: Set up Python
21
+ uses: actions/setup-python@v5
22
+ with:
23
+ python-version: "3.x"
24
+ - name: Install pypa/build
25
+ run: python3 -m pip install build --user
26
+ - name: Build a binary wheel and a source tarball
27
+ run: python3 -m build
28
+ - name: Store the distribution packages
29
+ uses: actions/upload-artifact@v4
30
+ with:
31
+ name: python-package-distributions
32
+ path: dist/
33
+
34
+ publish-to-pypi:
35
+ name: Publish to PyPI 🚀
36
+ needs:
37
+ - build
38
+ runs-on: ubuntu-latest
39
+ environment:
40
+ name: pypi
41
+ permissions:
42
+ id-token: write # Mandatory for PyPI Trusted Publishing
43
+
44
+ steps:
45
+ - name: Download all the dists
46
+ uses: actions/download-artifact@v4
47
+ with:
48
+ name: python-package-distributions
49
+ path: dist/
50
+ - name: Publish distribution 📦 to PyPI
51
+ uses: pypa/gh-action-pypi-publish@release/v1
runfn-0.1.0/.gitignore ADDED
@@ -0,0 +1,4 @@
1
+ venv/
2
+ dist/
3
+ __pycache__/
4
+ *.egg-info/
runfn-0.1.0/LICENSE ADDED
@@ -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.
runfn-0.1.0/PKG-INFO ADDED
@@ -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
+
runfn-0.1.0/README.md ADDED
@@ -0,0 +1,130 @@
1
+ # runfn
2
+
3
+ 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).
4
+
5
+ ---
6
+
7
+ ## Features
8
+
9
+ - **Zero-Boilerplate:** Run any function directly from any `.py` file without writing CLI wrappers or `if __name__ == '__main__':` blocks.
10
+ - **Output Assertions:** Use `--expect=VALUE` to assert expected results (supports literal values like numbers, booleans, lists, dicts, strings, and `None`).
11
+ - **Execution Timing:** Benchmark execution time in milliseconds with `--time_it`.
12
+ - **Built-in Safety:** Prevents invocation of private/internal attributes (`_...`), verifies callables, and checks file extensions.
13
+ - **CI/CD Friendly:** Deterministic exit codes for easy integration into test pipelines and scripts.
14
+
15
+ ---
16
+
17
+ ## Installation
18
+
19
+ ```bash
20
+ pip install runfn
21
+ ```
22
+
23
+ For development and running tests locally:
24
+
25
+ ```bash
26
+ pip install -e ".[dev]"
27
+ ```
28
+
29
+ ---
30
+
31
+ ## Usage
32
+
33
+ ### As a Python Library
34
+
35
+ ```python
36
+ import runfn
37
+
38
+ # Call any function dynamically and get its return value
39
+ result = runfn.run("myfile.py", "add", 2, 5)
40
+ print(result) # 7
41
+
42
+ # With keyword arguments
43
+ greeting = runfn.run("myfile.py", "greet", name="Sam")
44
+ print(greeting) # 'Hello Sam'
45
+ ```
46
+
47
+ ### From the Command Line (CLI)
48
+
49
+ ```bash
50
+ runfn myfile.py add 2 5
51
+ # Output:
52
+ # Result: 7
53
+ ```
54
+
55
+ ### Keyword Arguments
56
+
57
+ ```bash
58
+ runfn myfile.py greet --name=Sam
59
+ # Output:
60
+ # Result: 'Hello Sam'
61
+ ```
62
+
63
+ ### Assertions (`--expect`)
64
+
65
+ Compare the returned value against an expected literal:
66
+
67
+ ```bash
68
+ runfn myfile.py add 2 5 --expect=7
69
+ # Output:
70
+ # Result: 7
71
+ # PASS
72
+
73
+ runfn myfile.py add 2 5 --expect=8
74
+ # Output:
75
+ # Result: 7
76
+ # FAIL (expected 8)
77
+ ```
78
+
79
+ Functions returning `None` can also be checked:
80
+
81
+ ```bash
82
+ runfn myfile.py log_message "Hello" --expect=None
83
+ # PASS
84
+ ```
85
+
86
+ ### Execution Timing (`--time_it`)
87
+
88
+ Measure execution time of your function call:
89
+
90
+ ```bash
91
+ runfn myfile.py add 2 5 --expect=7 --time_it
92
+ # Output:
93
+ # Result: 7
94
+ # PASS
95
+ # Time: 0.042 ms
96
+ ```
97
+
98
+ ---
99
+
100
+ ## Exit Codes
101
+
102
+ | Exit Code | Meaning |
103
+ | :--- | :--- |
104
+ | **0** | Success (function ran and any `--expect` assertion passed). |
105
+ | **1** | Function execution failed or `--expect` assertion failed. |
106
+ | **2** | CLI / Target error (file not found, invalid `.py` extension, function not found, private attribute access, or non-callable). |
107
+
108
+ ---
109
+
110
+ ## Limitations & Safety
111
+
112
+ - Target functions cannot have arguments named `expect` or `time_it`, as these flags are reserved by the runner.
113
+ - Private functions or attributes (names starting with `_`) and non-callable attributes cannot be called.
114
+
115
+ ---
116
+
117
+ ## Running Tests
118
+
119
+ Run the test suite with `pytest`:
120
+
121
+ ```bash
122
+ pytest
123
+ ```
124
+
125
+ ---
126
+
127
+ ## License
128
+
129
+ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
130
+
@@ -0,0 +1,35 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "runfn"
7
+ version = "0.1.0"
8
+ description = "Run any Python function from the terminal, with expected-output checks and timing"
9
+ readme = "README.md"
10
+ requires-python = ">=3.8"
11
+ license = { file = "LICENSE" }
12
+ authors = [
13
+ { name = "Kavyansh Sharma", email = "kavyanshsharma2004@gmail.com" }
14
+ ]
15
+ dependencies = [
16
+ "fire",
17
+ ]
18
+ classifiers = [
19
+ "Programming Language :: Python :: 3",
20
+ "License :: OSI Approved :: MIT License",
21
+ "Operating System :: OS Independent",
22
+ ]
23
+
24
+ [project.optional-dependencies]
25
+ dev = [
26
+ "pytest",
27
+ ]
28
+
29
+ [project.urls]
30
+ Homepage = "https://github.com/KavyanshSharma09/runfn"
31
+ Repository = "https://github.com/KavyanshSharma09/runfn"
32
+ Issues = "https://github.com/KavyanshSharma09/runfn/issues"
33
+
34
+ [project.scripts]
35
+ runfn = "runfn.cli:main"
runfn-0.1.0/sample.py ADDED
@@ -0,0 +1,13 @@
1
+ def add(a, b):
2
+ return a + b
3
+
4
+ def greet(name):
5
+ return f"Hello {name}"
6
+
7
+ def say_hi(name):
8
+ print(f"Hi {name}")
9
+
10
+ SECRET_CONSTANT = 42
11
+
12
+ def _private_func():
13
+ return "hidden"
@@ -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__"]
@@ -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()
@@ -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
@@ -0,0 +1 @@
1
+
@@ -0,0 +1,62 @@
1
+ import subprocess, sys, pathlib
2
+
3
+ SAMPLE = str(pathlib.Path(__file__).parent.parent / "sample.py")
4
+
5
+ def run(*args):
6
+ return subprocess.run(
7
+ [sys.executable, "-m", "runfn.cli", SAMPLE, *args],
8
+ capture_output=True, text=True,
9
+ )
10
+
11
+ def test_result():
12
+ assert "Result: 7" in run("add", "2", "5").stdout
13
+
14
+ def test_pass():
15
+ r = run("add", "2", "5", "--expect=7")
16
+ assert "PASS" in r.stdout and r.returncode == 0
17
+
18
+ def test_fail_exit_code():
19
+ r = run("add", "2", "5", "--expect=8")
20
+ assert "FAIL" in r.stdout and r.returncode == 1
21
+
22
+ def test_string_kwarg():
23
+ r = run("greet", "--name=Sam", "--expect=Hello Sam")
24
+ assert "PASS" in r.stdout
25
+
26
+ def test_time():
27
+ assert "Time:" in run("add", "2", "5", "--time_it").stdout
28
+
29
+ def test_missing_function():
30
+ assert run("nope").returncode == 2
31
+
32
+ def test_no_return():
33
+ r = run("say_hi", "Sam")
34
+ assert "Hi Sam" in r.stdout
35
+ assert "no return value" in r.stdout and r.returncode == 0
36
+
37
+ def test_expect_none_passes():
38
+ r = run("say_hi", "Sam", "--expect=None")
39
+ assert "PASS" in r.stdout and r.returncode == 0
40
+
41
+ def test_expect_value_but_no_return_fails():
42
+ r = run("say_hi", "Sam", "--expect=5")
43
+ assert "returned nothing" in r.stdout and r.returncode == 1
44
+
45
+ def test_private_attribute_blocked():
46
+ r = run("_private_func")
47
+ assert r.returncode == 2
48
+ assert "private" in r.stdout or "private" in r.stderr
49
+
50
+ def test_non_callable_blocked():
51
+ r = run("SECRET_CONSTANT")
52
+ assert r.returncode == 2
53
+ assert "not callable" in r.stdout or "not callable" in r.stderr
54
+
55
+ def test_non_py_file_blocked():
56
+ license_file = str(pathlib.Path(__file__).parent.parent / "LICENSE")
57
+ r = subprocess.run(
58
+ [sys.executable, "-m", "runfn.cli", license_file, "add"],
59
+ capture_output=True, text=True,
60
+ )
61
+ assert r.returncode == 2
62
+ assert "must be a Python (.py) file" in r.stdout or "must be a Python (.py) file" in r.stderr
@@ -0,0 +1,42 @@
1
+ from pathlib import Path
2
+ import pytest
3
+ import runfn
4
+
5
+ SAMPLE = str(Path(__file__).parent.parent / "sample.py")
6
+
7
+
8
+ def test_library_import():
9
+ assert hasattr(runfn, "run")
10
+ assert hasattr(runfn, "run_fn")
11
+ assert runfn.__version__ == "0.1.0"
12
+
13
+
14
+ def test_library_call():
15
+ val = runfn.run(SAMPLE, "add", 3, 4)
16
+ assert val == 7
17
+
18
+
19
+ def test_library_greet():
20
+ val = runfn.run(SAMPLE, "greet", name="Sam")
21
+ assert val == "Hello Sam"
22
+
23
+
24
+ def test_library_missing_func():
25
+ with pytest.raises(AttributeError):
26
+ runfn.run(SAMPLE, "not_existing")
27
+
28
+
29
+ def test_library_private_func_blocked():
30
+ with pytest.raises(PermissionError):
31
+ runfn.run(SAMPLE, "_private_func")
32
+
33
+
34
+ def test_library_non_callable():
35
+ with pytest.raises(TypeError):
36
+ runfn.run(SAMPLE, "SECRET_CONSTANT")
37
+
38
+
39
+ def test_library_non_py_file():
40
+ license_file = str(Path(__file__).parent.parent / "LICENSE")
41
+ with pytest.raises(ValueError):
42
+ runfn.run(license_file, "add")