├── .gitignore ├── CHANGELOG.md ├── CONTRIBUTING.md ├── LICENSE ├── MANIFEST.in ├── Makefile ├── README.md ├── docs ├── .gitignore ├── Gemfile ├── Gemfile.lock ├── _config.yml ├── _data │ ├── sidebars │ │ └── home_sidebar.yml │ └── topnav.yml ├── feed.xml ├── index.html ├── sidebar.json └── sitemap.xml ├── index.ipynb ├── settings.ini ├── setup.py └── tinykernel ├── __init__.py ├── _nbdev.py └── compilerop.py /.gitignore: -------------------------------------------------------------------------------- 1 | conda/ 2 | *.bak 3 | .gitattributes 4 | .last_checked 5 | .gitconfig 6 | *.bak 7 | *.log 8 | *~ 9 | ~* 10 | _tmp* 11 | tmp* 12 | tags 13 | 14 | # Byte-compiled / optimized / DLL files 15 | __pycache__/ 16 | *.py[cod] 17 | *$py.class 18 | 19 | # C extensions 20 | *.so 21 | 22 | # Distribution / packaging 23 | .Python 24 | env/ 25 | build/ 26 | develop-eggs/ 27 | dist/ 28 | downloads/ 29 | eggs/ 30 | .eggs/ 31 | lib/ 32 | lib64/ 33 | parts/ 34 | sdist/ 35 | var/ 36 | wheels/ 37 | *.egg-info/ 38 | .installed.cfg 39 | *.egg 40 | 41 | # PyInstaller 42 | # Usually these files are written by a python script from a template 43 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 44 | *.manifest 45 | *.spec 46 | 47 | # Installer logs 48 | pip-log.txt 49 | pip-delete-this-directory.txt 50 | 51 | # Unit test / coverage reports 52 | htmlcov/ 53 | .tox/ 54 | .coverage 55 | .coverage.* 56 | .cache 57 | nosetests.xml 58 | coverage.xml 59 | *.cover 60 | .hypothesis/ 61 | 62 | # Translations 63 | *.mo 64 | *.pot 65 | 66 | # Django stuff: 67 | *.log 68 | local_settings.py 69 | 70 | # Flask stuff: 71 | instance/ 72 | .webassets-cache 73 | 74 | # Scrapy stuff: 75 | .scrapy 76 | 77 | # Sphinx documentation 78 | docs/_build/ 79 | 80 | # PyBuilder 81 | target/ 82 | 83 | # Jupyter Notebook 84 | .ipynb_checkpoints 85 | 86 | # pyenv 87 | .python-version 88 | 89 | # celery beat schedule file 90 | celerybeat-schedule 91 | 92 | # SageMath parsed files 93 | *.sage.py 94 | 95 | # dotenv 96 | .env 97 | 98 | # virtualenv 99 | .venv 100 | venv/ 101 | ENV/ 102 | 103 | # Spyder project settings 104 | .spyderproject 105 | .spyproject 106 | 107 | # Rope project settings 108 | .ropeproject 109 | 110 | # mkdocs documentation 111 | /site 112 | 113 | # mypy 114 | .mypy_cache/ 115 | 116 | .vscode 117 | *.swp 118 | 119 | # osx generated files 120 | .DS_Store 121 | .DS_Store? 122 | .Trashes 123 | ehthumbs.db 124 | Thumbs.db 125 | .idea 126 | 127 | # pytest 128 | .pytest_cache 129 | 130 | # tools/trust-doc-nbs 131 | docs_src/.last_checked 132 | 133 | # symlinks to fastai 134 | docs_src/fastai 135 | tools/fastai 136 | 137 | # link checker 138 | checklink/cookies.txt 139 | 140 | # .gitconfig is now autogenerated 141 | .gitconfig 142 | 143 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Release notes 2 | 3 | 4 | 5 | ## 0.0.2 6 | 7 | ### New Features 8 | 9 | - Add `name` param to ctor ([#1](https://github.com/fastai/tinykernel/issues/1)) 10 | 11 | 12 | ## 0.0.1 13 | 14 | - Initial version 15 | 16 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # How to contribute 2 | 3 | ## How to get started 4 | 5 | Before anything else, please install the git hooks that run automatic scripts during each commit and merge to strip the notebooks of superfluous metadata (and avoid merge conflicts). After cloning the repository, run the following command inside it: 6 | ``` 7 | nbdev_install_git_hooks 8 | ``` 9 | 10 | ## Did you find a bug? 11 | 12 | * Ensure the bug was not already reported by searching on GitHub under Issues. 13 | * If you're unable to find an open issue addressing the problem, open a new one. Be sure to include a title and clear description, as much relevant information as possible, and a code sample or an executable test case demonstrating the expected behavior that is not occurring. 14 | * Be sure to add the complete error messages. 15 | 16 | #### Did you write a patch that fixes a bug? 17 | 18 | * Open a new GitHub pull request with the patch. 19 | * Ensure that your PR includes a test that fails without your patch, and pass with it. 20 | * Ensure the PR description clearly describes the problem and solution. Include the relevant issue number if applicable. 21 | 22 | ## PR submission guidelines 23 | 24 | * Keep each PR focused. While it's more convenient, do not combine several unrelated fixes together. Create as many branches as needing to keep each PR focused. 25 | * Do not mix style changes/fixes with "functional" changes. It's very difficult to review such PRs and it most likely get rejected. 26 | * Do not add/remove vertical whitespace. Preserve the original style of the file you edit as much as you can. 27 | * Do not turn an already submitted PR into your development playground. If after you submitted PR, you discovered that more work is needed - close the PR, do the required work and then submit a new PR. Otherwise each of your commits requires attention from maintainers of the project. 28 | * If, however, you submitted a PR and received a request for changes, you should proceed with commits inside that PR, so that the maintainer can see the incremental fixes and won't need to review the whole PR again. In the exception case where you realize it'll take many many commits to complete the requests, then it's probably best to close the PR, do the work and then submit it again. Use common sense where you'd choose one way over another. 29 | 30 | ## Do you want to contribute to the documentation? 31 | 32 | * Docs are automatically created from the notebooks in the nbs folder. 33 | 34 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include settings.ini 2 | include LICENSE 3 | include CONTRIBUTING.md 4 | include README.md 5 | recursive-exclude * __pycache__ 6 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | .ONESHELL: 2 | SHELL := /bin/bash 3 | SRC = $(wildcard ./*.ipynb) 4 | 5 | all: tinykernel docs 6 | 7 | tinykernel: $(SRC) 8 | nbdev_build_lib 9 | touch tinykernel 10 | 11 | sync: 12 | nbdev_update_lib 13 | 14 | docs_serve: docs 15 | cd docs && bundle exec jekyll serve 16 | 17 | docs: $(SRC) 18 | nbdev_build_docs 19 | touch docs 20 | 21 | test: 22 | nbdev_test_nbs 23 | 24 | release: pypi conda_release 25 | nbdev_bump_version 26 | 27 | conda_release: 28 | fastrelease_conda_package 29 | 30 | pypi: dist 31 | twine upload --repository pypi dist/* 32 | 33 | dist: clean 34 | python setup.py sdist bdist_wheel 35 | 36 | clean: 37 | rm -rf dist -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # tinykernel 2 | > A minimal Python kernel, so you can run Python in your Python. 3 | 4 | 5 | All the clever stuff in this library is provided by Python's builtin `ast` module and compilation/exec/eval system, along with [IPython](https://ipython.org/)'s `CachingCompiler` which does some [deep magic](https://cprohm.de/article/better-test-output-with-ast-rewriting-and-a-patched-standard-library.html/). `tinykernel` just brings them together with a little glue. 6 | 7 | ## Install 8 | 9 | With pip: 10 | 11 | pip install tinykernel 12 | 13 | With conda: 14 | 15 | conda install -c fastai tinykernel 16 | 17 | ## How to use 18 | 19 | This library provides a single class, `TinyKernel`, which is a tiny persistent kernel for Python code: 20 | 21 | ```python 22 | k = TinyKernel() 23 | ``` 24 | 25 | Call it, passing Python code, to have the code executed in a separate Python environment: 26 | 27 | ```python 28 | k("a=1") 29 | ``` 30 | 31 | Expressions return the value of the expression: 32 | 33 | ```python 34 | k('a') 35 | ``` 36 | 37 | 38 | 39 | 40 | 1 41 | 42 | 43 | 44 | All variables are persisted across calls: 45 | 46 | ```python 47 | k("a+=1") 48 | k('a') 49 | ``` 50 | 51 | 52 | 53 | 54 | 2 55 | 56 | 57 | 58 | Multi-line inputs are supported. If the last line is an expression, it is returned: 59 | 60 | ```python 61 | k("""import types 62 | b = types.SimpleNamespace(foo=a) 63 | b""") 64 | ``` 65 | 66 | 67 | 68 | 69 | namespace(foo=2) 70 | 71 | 72 | 73 | The original source code is stored, so `inspect.getsource` works and, tracebacks have full details. 74 | 75 | ```python 76 | k("""def f(): pass # a comment 77 | import inspect 78 | inspect.getsource(f)""") 79 | ``` 80 | 81 | 82 | 83 | 84 | 'def f(): pass # a comment\n' 85 | 86 | 87 | 88 | When creating a `TinyKernel`, you can pass a dict of globals to initialize the environment: 89 | 90 | ```python 91 | k = TinyKernel(glb={'foo':'bar'}) 92 | k('foo*2') 93 | ``` 94 | 95 | 96 | 97 | 98 | 'barbar' 99 | 100 | 101 | 102 | Pass `name` to customize the string that appears in tracebacks ("kernel" by default): 103 | 104 | ```python 105 | k = TinyKernel(name='myapp') 106 | code = '''def f(): 107 | return 1/0 108 | print(f())''' 109 | try: k(code) 110 | except Exception as e: print(traceback.format_exc()) 111 | ``` 112 | 113 | Traceback (most recent call last): 114 | File "", line 5, in 115 | try: k(code) 116 | File "/home/jhoward/git/tinykernel/tinykernel/__init__.py", line 20, in __call__ 117 | if expr: return self._run(Expression(expr.value), nm, 'eval') 118 | File "/home/jhoward/git/tinykernel/tinykernel/__init__.py", line 12, in _run 119 | def _run(self, p, nm, mode='exec'): return eval(compiler(p, nm, mode), self.glb) 120 | File "", line 3, in 121 | print(f()) 122 | File "", line 2, in f 123 | return 1/0 124 | ZeroDivisionError: division by zero 125 | 126 | 127 | 128 | ## Acknowledgements 129 | 130 | Thanks to Christopher Prohm, Matthias Bussonnier, and Aaron Meurer for their helpful insights in [this twitter thread](https://twitter.com/jeremyphoward/status/1424990665746763781). 131 | -------------------------------------------------------------------------------- /docs/.gitignore: -------------------------------------------------------------------------------- 1 | _site/ 2 | -------------------------------------------------------------------------------- /docs/Gemfile: -------------------------------------------------------------------------------- 1 | source "https://rubygems.org" 2 | 3 | gem 'github-pages', group: :jekyll_plugins 4 | 5 | # Added at 2019-11-25 10:11:40 -0800 by jhoward: 6 | gem "nokogiri", "< 1.11.1" 7 | gem "jekyll", ">= 3.7" 8 | gem "kramdown", ">= 2.3.0" 9 | gem "jekyll-remote-theme" 10 | -------------------------------------------------------------------------------- /docs/Gemfile.lock: -------------------------------------------------------------------------------- 1 | GEM 2 | remote: https://rubygems.org/ 3 | specs: 4 | activesupport (6.0.3.4) 5 | concurrent-ruby (~> 1.0, >= 1.0.2) 6 | i18n (>= 0.7, < 2) 7 | minitest (~> 5.1) 8 | tzinfo (~> 1.1) 9 | zeitwerk (~> 2.2, >= 2.2.2) 10 | addressable (2.7.0) 11 | public_suffix (>= 2.0.2, < 5.0) 12 | coffee-script (2.4.1) 13 | coffee-script-source 14 | execjs 15 | coffee-script-source (1.11.1) 16 | colorator (1.1.0) 17 | commonmarker (0.17.13) 18 | ruby-enum (~> 0.5) 19 | concurrent-ruby (1.1.7) 20 | dnsruby (1.61.5) 21 | simpleidn (~> 0.1) 22 | em-websocket (0.5.2) 23 | eventmachine (>= 0.12.9) 24 | http_parser.rb (~> 0.6.0) 25 | ethon (0.12.0) 26 | ffi (>= 1.3.0) 27 | eventmachine (1.2.7) 28 | execjs (2.7.0) 29 | faraday (1.3.0) 30 | faraday-net_http (~> 1.0) 31 | multipart-post (>= 1.2, < 3) 32 | ruby2_keywords 33 | faraday-net_http (1.0.1) 34 | ffi (1.14.2) 35 | forwardable-extended (2.6.0) 36 | gemoji (3.0.1) 37 | github-pages (209) 38 | github-pages-health-check (= 1.16.1) 39 | jekyll (= 3.9.0) 40 | jekyll-avatar (= 0.7.0) 41 | jekyll-coffeescript (= 1.1.1) 42 | jekyll-commonmark-ghpages (= 0.1.6) 43 | jekyll-default-layout (= 0.1.4) 44 | jekyll-feed (= 0.15.1) 45 | jekyll-gist (= 1.5.0) 46 | jekyll-github-metadata (= 2.13.0) 47 | jekyll-mentions (= 1.6.0) 48 | jekyll-optional-front-matter (= 0.3.2) 49 | jekyll-paginate (= 1.1.0) 50 | jekyll-readme-index (= 0.3.0) 51 | jekyll-redirect-from (= 0.16.0) 52 | jekyll-relative-links (= 0.6.1) 53 | jekyll-remote-theme (= 0.4.2) 54 | jekyll-sass-converter (= 1.5.2) 55 | jekyll-seo-tag (= 2.6.1) 56 | jekyll-sitemap (= 1.4.0) 57 | jekyll-swiss (= 1.0.0) 58 | jekyll-theme-architect (= 0.1.1) 59 | jekyll-theme-cayman (= 0.1.1) 60 | jekyll-theme-dinky (= 0.1.1) 61 | jekyll-theme-hacker (= 0.1.2) 62 | jekyll-theme-leap-day (= 0.1.1) 63 | jekyll-theme-merlot (= 0.1.1) 64 | jekyll-theme-midnight (= 0.1.1) 65 | jekyll-theme-minimal (= 0.1.1) 66 | jekyll-theme-modernist (= 0.1.1) 67 | jekyll-theme-primer (= 0.5.4) 68 | jekyll-theme-slate (= 0.1.1) 69 | jekyll-theme-tactile (= 0.1.1) 70 | jekyll-theme-time-machine (= 0.1.1) 71 | jekyll-titles-from-headings (= 0.5.3) 72 | jemoji (= 0.12.0) 73 | kramdown (= 2.3.0) 74 | kramdown-parser-gfm (= 1.1.0) 75 | liquid (= 4.0.3) 76 | mercenary (~> 0.3) 77 | minima (= 2.5.1) 78 | nokogiri (>= 1.10.4, < 2.0) 79 | rouge (= 3.23.0) 80 | terminal-table (~> 1.4) 81 | github-pages-health-check (1.16.1) 82 | addressable (~> 2.3) 83 | dnsruby (~> 1.60) 84 | octokit (~> 4.0) 85 | public_suffix (~> 3.0) 86 | typhoeus (~> 1.3) 87 | html-pipeline (2.14.0) 88 | activesupport (>= 2) 89 | nokogiri (>= 1.4) 90 | http_parser.rb (0.6.0) 91 | i18n (0.9.5) 92 | concurrent-ruby (~> 1.0) 93 | jekyll (3.9.0) 94 | addressable (~> 2.4) 95 | colorator (~> 1.0) 96 | em-websocket (~> 0.5) 97 | i18n (~> 0.7) 98 | jekyll-sass-converter (~> 1.0) 99 | jekyll-watch (~> 2.0) 100 | kramdown (>= 1.17, < 3) 101 | liquid (~> 4.0) 102 | mercenary (~> 0.3.3) 103 | pathutil (~> 0.9) 104 | rouge (>= 1.7, < 4) 105 | safe_yaml (~> 1.0) 106 | jekyll-avatar (0.7.0) 107 | jekyll (>= 3.0, < 5.0) 108 | jekyll-coffeescript (1.1.1) 109 | coffee-script (~> 2.2) 110 | coffee-script-source (~> 1.11.1) 111 | jekyll-commonmark (1.3.1) 112 | commonmarker (~> 0.14) 113 | jekyll (>= 3.7, < 5.0) 114 | jekyll-commonmark-ghpages (0.1.6) 115 | commonmarker (~> 0.17.6) 116 | jekyll-commonmark (~> 1.2) 117 | rouge (>= 2.0, < 4.0) 118 | jekyll-default-layout (0.1.4) 119 | jekyll (~> 3.0) 120 | jekyll-feed (0.15.1) 121 | jekyll (>= 3.7, < 5.0) 122 | jekyll-gist (1.5.0) 123 | octokit (~> 4.2) 124 | jekyll-github-metadata (2.13.0) 125 | jekyll (>= 3.4, < 5.0) 126 | octokit (~> 4.0, != 4.4.0) 127 | jekyll-mentions (1.6.0) 128 | html-pipeline (~> 2.3) 129 | jekyll (>= 3.7, < 5.0) 130 | jekyll-optional-front-matter (0.3.2) 131 | jekyll (>= 3.0, < 5.0) 132 | jekyll-paginate (1.1.0) 133 | jekyll-readme-index (0.3.0) 134 | jekyll (>= 3.0, < 5.0) 135 | jekyll-redirect-from (0.16.0) 136 | jekyll (>= 3.3, < 5.0) 137 | jekyll-relative-links (0.6.1) 138 | jekyll (>= 3.3, < 5.0) 139 | jekyll-remote-theme (0.4.2) 140 | addressable (~> 2.0) 141 | jekyll (>= 3.5, < 5.0) 142 | jekyll-sass-converter (>= 1.0, <= 3.0.0, != 2.0.0) 143 | rubyzip (>= 1.3.0, < 3.0) 144 | jekyll-sass-converter (1.5.2) 145 | sass (~> 3.4) 146 | jekyll-seo-tag (2.6.1) 147 | jekyll (>= 3.3, < 5.0) 148 | jekyll-sitemap (1.4.0) 149 | jekyll (>= 3.7, < 5.0) 150 | jekyll-swiss (1.0.0) 151 | jekyll-theme-architect (0.1.1) 152 | jekyll (~> 3.5) 153 | jekyll-seo-tag (~> 2.0) 154 | jekyll-theme-cayman (0.1.1) 155 | jekyll (~> 3.5) 156 | jekyll-seo-tag (~> 2.0) 157 | jekyll-theme-dinky (0.1.1) 158 | jekyll (~> 3.5) 159 | jekyll-seo-tag (~> 2.0) 160 | jekyll-theme-hacker (0.1.2) 161 | jekyll (> 3.5, < 5.0) 162 | jekyll-seo-tag (~> 2.0) 163 | jekyll-theme-leap-day (0.1.1) 164 | jekyll (~> 3.5) 165 | jekyll-seo-tag (~> 2.0) 166 | jekyll-theme-merlot (0.1.1) 167 | jekyll (~> 3.5) 168 | jekyll-seo-tag (~> 2.0) 169 | jekyll-theme-midnight (0.1.1) 170 | jekyll (~> 3.5) 171 | jekyll-seo-tag (~> 2.0) 172 | jekyll-theme-minimal (0.1.1) 173 | jekyll (~> 3.5) 174 | jekyll-seo-tag (~> 2.0) 175 | jekyll-theme-modernist (0.1.1) 176 | jekyll (~> 3.5) 177 | jekyll-seo-tag (~> 2.0) 178 | jekyll-theme-primer (0.5.4) 179 | jekyll (> 3.5, < 5.0) 180 | jekyll-github-metadata (~> 2.9) 181 | jekyll-seo-tag (~> 2.0) 182 | jekyll-theme-slate (0.1.1) 183 | jekyll (~> 3.5) 184 | jekyll-seo-tag (~> 2.0) 185 | jekyll-theme-tactile (0.1.1) 186 | jekyll (~> 3.5) 187 | jekyll-seo-tag (~> 2.0) 188 | jekyll-theme-time-machine (0.1.1) 189 | jekyll (~> 3.5) 190 | jekyll-seo-tag (~> 2.0) 191 | jekyll-titles-from-headings (0.5.3) 192 | jekyll (>= 3.3, < 5.0) 193 | jekyll-watch (2.2.1) 194 | listen (~> 3.0) 195 | jemoji (0.12.0) 196 | gemoji (~> 3.0) 197 | html-pipeline (~> 2.2) 198 | jekyll (>= 3.0, < 5.0) 199 | kramdown (2.3.0) 200 | rexml 201 | kramdown-parser-gfm (1.1.0) 202 | kramdown (~> 2.0) 203 | liquid (4.0.3) 204 | listen (3.4.0) 205 | rb-fsevent (~> 0.10, >= 0.10.3) 206 | rb-inotify (~> 0.9, >= 0.9.10) 207 | mercenary (0.3.6) 208 | mini_portile2 (2.5.0) 209 | minima (2.5.1) 210 | jekyll (>= 3.5, < 5.0) 211 | jekyll-feed (~> 0.9) 212 | jekyll-seo-tag (~> 2.1) 213 | minitest (5.14.3) 214 | multipart-post (2.1.1) 215 | nokogiri (1.11.0) 216 | mini_portile2 (~> 2.5.0) 217 | racc (~> 1.4) 218 | octokit (4.20.0) 219 | faraday (>= 0.9) 220 | sawyer (~> 0.8.0, >= 0.5.3) 221 | pathutil (0.16.2) 222 | forwardable-extended (~> 2.6) 223 | public_suffix (3.1.1) 224 | racc (1.5.2) 225 | rb-fsevent (0.10.4) 226 | rb-inotify (0.10.1) 227 | ffi (~> 1.0) 228 | rexml (3.2.4) 229 | rouge (3.23.0) 230 | ruby-enum (0.8.0) 231 | i18n 232 | ruby2_keywords (0.0.2) 233 | rubyzip (2.3.0) 234 | safe_yaml (1.0.5) 235 | sass (3.7.4) 236 | sass-listen (~> 4.0.0) 237 | sass-listen (4.0.0) 238 | rb-fsevent (~> 0.9, >= 0.9.4) 239 | rb-inotify (~> 0.9, >= 0.9.7) 240 | sawyer (0.8.2) 241 | addressable (>= 2.3.5) 242 | faraday (> 0.8, < 2.0) 243 | simpleidn (0.1.1) 244 | unf (~> 0.1.4) 245 | terminal-table (1.8.0) 246 | unicode-display_width (~> 1.1, >= 1.1.1) 247 | thread_safe (0.3.6) 248 | typhoeus (1.4.0) 249 | ethon (>= 0.9.0) 250 | tzinfo (1.2.9) 251 | thread_safe (~> 0.1) 252 | unf (0.1.4) 253 | unf_ext 254 | unf_ext (0.0.7.7) 255 | unicode-display_width (1.7.0) 256 | zeitwerk (2.4.2) 257 | 258 | PLATFORMS 259 | ruby 260 | 261 | DEPENDENCIES 262 | github-pages 263 | jekyll (>= 3.7) 264 | jekyll-remote-theme 265 | kramdown (>= 2.3.0) 266 | nokogiri (< 1.11.1) 267 | 268 | BUNDLED WITH 269 | 2.1.4 270 | -------------------------------------------------------------------------------- /docs/_config.yml: -------------------------------------------------------------------------------- 1 | repository: fastai/tinykernel 2 | output: web 3 | topnav_title: tinykernel 4 | site_title: tinykernel 5 | company_name: 2021 onwards, Jeremy Howard 6 | description: A minimal Python kernel so you can run Python in your Python 7 | # Set to false to disable KaTeX math 8 | use_math: true 9 | # Add Google analytics id if you have one and want to use it here 10 | google_analytics: 11 | # See http://nbdev.fast.ai/search for help with adding Search 12 | google_search: 13 | 14 | host: 127.0.0.1 15 | # the preview server used. Leave as is. 16 | port: 4000 17 | # the port where the preview is rendered. 18 | 19 | default_badges: 20 | colab: true 21 | 22 | exclude: 23 | - .idea/ 24 | - .gitignore 25 | - vendor 26 | 27 | exclude: [vendor] 28 | 29 | highlighter: rouge 30 | markdown: kramdown 31 | kramdown: 32 | input: GFM 33 | auto_ids: true 34 | hard_wrap: false 35 | syntax_highlighter: rouge 36 | 37 | collections: 38 | tooltips: 39 | output: false 40 | 41 | defaults: 42 | - 43 | scope: 44 | path: "" 45 | type: "pages" 46 | values: 47 | layout: "page" 48 | comments: true 49 | search: true 50 | sidebar: home_sidebar 51 | topnav: topnav 52 | - 53 | scope: 54 | path: "" 55 | type: "tooltips" 56 | values: 57 | layout: "page" 58 | comments: true 59 | search: true 60 | tooltip: true 61 | 62 | sidebars: 63 | - home_sidebar 64 | 65 | plugins: 66 | - jekyll-remote-theme 67 | 68 | remote_theme: fastai/nbdev-jekyll-theme 69 | baseurl: /tinykernel/ 70 | -------------------------------------------------------------------------------- /docs/_data/sidebars/home_sidebar.yml: -------------------------------------------------------------------------------- 1 | 2 | ################################################# 3 | ### THIS FILE WAS AUTOGENERATED! DO NOT EDIT! ### 4 | ################################################# 5 | # Instead edit ../../sidebar.json 6 | entries: 7 | - folders: 8 | - folderitems: 9 | - output: web,pdf 10 | title: Overview 11 | url: / 12 | output: web 13 | title: tinykernel 14 | output: web 15 | title: Sidebar 16 | -------------------------------------------------------------------------------- /docs/_data/topnav.yml: -------------------------------------------------------------------------------- 1 | topnav: 2 | - title: Topnav 3 | items: 4 | - title: github 5 | external_url: https://github.com/fastai/tinykernel/tree/master/ 6 | 7 | #Topnav dropdowns 8 | topnav_dropdowns: 9 | - title: Topnav dropdowns 10 | folders: -------------------------------------------------------------------------------- /docs/feed.xml: -------------------------------------------------------------------------------- 1 | --- 2 | search: exclude 3 | layout: none 4 | --- 5 | 6 | 7 | 8 | 9 | {{ site.title | xml_escape }} 10 | {{ site.description | xml_escape }} 11 | {{ site.url }}/ 12 | 13 | {{ site.time | date_to_rfc822 }} 14 | {{ site.time | date_to_rfc822 }} 15 | Jekyll v{{ jekyll.version }} 16 | {% for post in site.posts limit:10 %} 17 | 18 | {{ post.title | xml_escape }} 19 | {{ post.content | xml_escape }} 20 | {{ post.date | date_to_rfc822 }} 21 | {{ post.url | prepend: site.url }} 22 | {{ post.url | prepend: site.url }} 23 | {% for tag in post.tags %} 24 | {{ tag | xml_escape }} 25 | {% endfor %} 26 | {% for tag in page.tags %} 27 | {{ cat | xml_escape }} 28 | {% endfor %} 29 | 30 | {% endfor %} 31 | 32 | 33 | -------------------------------------------------------------------------------- /docs/index.html: -------------------------------------------------------------------------------- 1 | --- 2 | 3 | title: tinykernel 4 | 5 | 6 | keywords: fastai 7 | sidebar: home_sidebar 8 | 9 | summary: "A minimal Python kernel, so you can run Python in your Python." 10 | description: "A minimal Python kernel, so you can run Python in your Python." 11 | nb_path: "index.ipynb" 12 | --- 13 | 22 | 23 |
24 | 25 | {% raw %} 26 | 27 |
28 | 29 |
30 | {% endraw %} 31 | 32 |
33 |
34 |

All the clever stuff in this library is provided by Python's builtin ast module and compilation/exec/eval system, along with IPython's CachingCompiler which does some deep magic. tinykernel just brings them together with a little glue.

35 | 36 |
37 |
38 |
39 |
40 |
41 |

Install

42 |
43 |
44 |
45 |
46 |
47 |

With pip:

48 | 49 |
pip install tinykernel
 50 | 
 51 | 
52 |

With conda:

53 | 54 |
conda install -c fastai tinykernel
55 | 56 |
57 |
58 |
59 |
60 |
61 |

How to use

62 |
63 |
64 |
65 |
66 |
67 |

This library provides a single class, TinyKernel, which is a tiny persistent kernel for Python code:

68 | 69 |
70 |
71 |
72 | {% raw %} 73 | 74 |
75 |
76 | 77 |
78 |
79 |
k = TinyKernel()
 80 | 
81 | 82 |
83 |
84 |
85 | 86 |
87 | {% endraw %} 88 | 89 |
90 |
91 |

Call it, passing Python code, to have the code executed in a separate Python environment:

92 | 93 |
94 |
95 |
96 | {% raw %} 97 | 98 |
99 |
100 | 101 |
102 |
103 |
k("a=1")
104 | 
105 | 106 |
107 |
108 |
109 | 110 |
111 | {% endraw %} 112 | 113 |
114 |
115 |

Expressions return the value of the expression:

116 | 117 |
118 |
119 |
120 | {% raw %} 121 | 122 |
123 |
124 | 125 |
126 |
127 |
k('a')
128 | 
129 | 130 |
131 |
132 |
133 | 134 |
135 |
136 | 137 |
138 | 139 | 140 | 141 |
142 |
1
143 |
144 | 145 |
146 | 147 |
148 |
149 | 150 |
151 | {% endraw %} 152 | 153 |
154 |
155 |

All variables are persisted across calls:

156 | 157 |
158 |
159 |
160 | {% raw %} 161 | 162 |
163 |
164 | 165 |
166 |
167 |
k("a+=1")
168 | k('a')
169 | 
170 | 171 |
172 |
173 |
174 | 175 |
176 |
177 | 178 |
179 | 180 | 181 | 182 |
183 |
2
184 |
185 | 186 |
187 | 188 |
189 |
190 | 191 |
192 | {% endraw %} 193 | 194 |
195 |
196 |

Multi-line inputs are supported. If the last line is an expression, it is returned:

197 | 198 |
199 |
200 |
201 | {% raw %} 202 | 203 |
204 |
205 | 206 |
207 |
208 |
k("""import types
209 | b = types.SimpleNamespace(foo=a)
210 | b""")
211 | 
212 | 213 |
214 |
215 |
216 | 217 |
218 |
219 | 220 |
221 | 222 | 223 | 224 |
225 |
namespace(foo=2)
226 |
227 | 228 |
229 | 230 |
231 |
232 | 233 |
234 | {% endraw %} 235 | 236 |
237 |
238 |

The original source code is stored, so inspect.getsource works and, tracebacks have full details.

239 | 240 |
241 |
242 |
243 | {% raw %} 244 | 245 |
246 |
247 | 248 |
249 |
250 |
k("""def f(): pass # a comment
251 | import inspect
252 | inspect.getsource(f)""")
253 | 
254 | 255 |
256 |
257 |
258 | 259 |
260 |
261 | 262 |
263 | 264 | 265 | 266 |
267 |
'def f(): pass # a comment\n'
268 |
269 | 270 |
271 | 272 |
273 |
274 | 275 |
276 | {% endraw %} 277 | 278 |
279 |
280 |

When creating a TinyKernel, you can pass a dict of globals to initialize the environment:

281 | 282 |
283 |
284 |
285 | {% raw %} 286 | 287 |
288 |
289 | 290 |
291 |
292 |
k = TinyKernel(glb={'foo':'bar'})
293 | k('foo*2')
294 | 
295 | 296 |
297 |
298 |
299 | 300 |
301 |
302 | 303 |
304 | 305 | 306 | 307 |
308 |
'barbar'
309 |
310 | 311 |
312 | 313 |
314 |
315 | 316 |
317 | {% endraw %} 318 | 319 |
320 |
321 |

Pass name to customize the string that appears in tracebacks ("kernel" by default):

322 | 323 |
324 |
325 |
326 | {% raw %} 327 | 328 |
329 |
330 | 331 |
332 |
333 |
k = TinyKernel(name='myapp')
334 | code = '''def f():
335 |     return 1/0
336 | print(f())'''
337 | try: k(code)
338 | except Exception as e: print(traceback.format_exc())
339 | 
340 | 341 |
342 |
343 |
344 | 345 |
346 |
347 | 348 |
349 | 350 |
351 |
Traceback (most recent call last):
352 |   File "<ipython-input-37-8b370e64c5cb>", line 5, in <module>
353 |     try: k(code)
354 |   File "/home/jhoward/git/tinykernel/tinykernel/__init__.py", line 20, in __call__
355 |     if expr: return self._run(Expression(expr.value), nm, 'eval')
356 |   File "/home/jhoward/git/tinykernel/tinykernel/__init__.py", line 12, in _run
357 |     def _run(self, p, nm, mode='exec'): return eval(compiler(p, nm, mode), self.glb)
358 |   File "<myapp--1-57331cf14e08>", line 3, in <module>
359 |     print(f())
360 |   File "<myapp--1-57331cf14e08>", line 2, in f
361 |     return 1/0
362 | ZeroDivisionError: division by zero
363 | 
364 | 
365 |
366 |
367 | 368 |
369 |
370 | 371 |
372 | {% endraw %} 373 | 374 |
375 |
376 |

Acknowledgements

377 |
378 |
379 |
380 |
381 |
382 |

Thanks to Christopher Prohm, Matthias Bussonnier, and Aaron Meurer for their helpful insights in this twitter thread.

383 | 384 |
385 |
386 |
387 |
388 | 389 | 390 | -------------------------------------------------------------------------------- /docs/sidebar.json: -------------------------------------------------------------------------------- 1 | { 2 | "tinykernel": { 3 | "Overview": "/" 4 | } 5 | } -------------------------------------------------------------------------------- /docs/sitemap.xml: -------------------------------------------------------------------------------- 1 | --- 2 | layout: none 3 | search: exclude 4 | --- 5 | 6 | 7 | 8 | {% for post in site.posts %} 9 | {% unless post.search == "exclude" %} 10 | 11 | {{site.url}}{{post.url}} 12 | 13 | {% endunless %} 14 | {% endfor %} 15 | 16 | 17 | {% for page in site.pages %} 18 | {% unless page.search == "exclude" %} 19 | 20 | {{site.url}}{{ page.url}} 21 | 22 | {% endunless %} 23 | {% endfor %} 24 | -------------------------------------------------------------------------------- /index.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": null, 6 | "metadata": {}, 7 | "outputs": [], 8 | "source": [ 9 | "#hide\n", 10 | "from tinykernel import *" 11 | ] 12 | }, 13 | { 14 | "cell_type": "markdown", 15 | "metadata": {}, 16 | "source": [ 17 | "# tinykernel\n", 18 | "\n", 19 | "> A minimal Python kernel, so you can run Python in your Python." 20 | ] 21 | }, 22 | { 23 | "cell_type": "markdown", 24 | "metadata": {}, 25 | "source": [ 26 | "All the clever stuff in this library is provided by Python's builtin `ast` module and compilation/exec/eval system, along with [IPython](https://ipython.org/)'s `CachingCompiler` which does some [deep magic](https://cprohm.de/article/better-test-output-with-ast-rewriting-and-a-patched-standard-library.html/). `tinykernel` just brings them together with a little glue." 27 | ] 28 | }, 29 | { 30 | "cell_type": "markdown", 31 | "metadata": {}, 32 | "source": [ 33 | "## Install" 34 | ] 35 | }, 36 | { 37 | "cell_type": "markdown", 38 | "metadata": {}, 39 | "source": [ 40 | "With pip:\n", 41 | "\n", 42 | " pip install tinykernel\n", 43 | "\n", 44 | "With conda:\n", 45 | "\n", 46 | " conda install -c fastai tinykernel" 47 | ] 48 | }, 49 | { 50 | "cell_type": "markdown", 51 | "metadata": {}, 52 | "source": [ 53 | "## How to use" 54 | ] 55 | }, 56 | { 57 | "cell_type": "markdown", 58 | "metadata": {}, 59 | "source": [ 60 | "This library provides a single class, `TinyKernel`, which is a tiny persistent kernel for Python code:" 61 | ] 62 | }, 63 | { 64 | "cell_type": "code", 65 | "execution_count": null, 66 | "metadata": {}, 67 | "outputs": [], 68 | "source": [ 69 | "k = TinyKernel()" 70 | ] 71 | }, 72 | { 73 | "cell_type": "markdown", 74 | "metadata": {}, 75 | "source": [ 76 | "Call it, passing Python code, to have the code executed in a separate Python environment:" 77 | ] 78 | }, 79 | { 80 | "cell_type": "code", 81 | "execution_count": null, 82 | "metadata": {}, 83 | "outputs": [], 84 | "source": [ 85 | "k(\"a=1\")" 86 | ] 87 | }, 88 | { 89 | "cell_type": "markdown", 90 | "metadata": {}, 91 | "source": [ 92 | "Expressions return the value of the expression:" 93 | ] 94 | }, 95 | { 96 | "cell_type": "code", 97 | "execution_count": null, 98 | "metadata": {}, 99 | "outputs": [ 100 | { 101 | "data": { 102 | "text/plain": [ 103 | "1" 104 | ] 105 | }, 106 | "execution_count": null, 107 | "metadata": {}, 108 | "output_type": "execute_result" 109 | } 110 | ], 111 | "source": [ 112 | "k('a')" 113 | ] 114 | }, 115 | { 116 | "cell_type": "markdown", 117 | "metadata": {}, 118 | "source": [ 119 | "All variables are persisted across calls:" 120 | ] 121 | }, 122 | { 123 | "cell_type": "code", 124 | "execution_count": null, 125 | "metadata": {}, 126 | "outputs": [ 127 | { 128 | "data": { 129 | "text/plain": [ 130 | "2" 131 | ] 132 | }, 133 | "execution_count": null, 134 | "metadata": {}, 135 | "output_type": "execute_result" 136 | } 137 | ], 138 | "source": [ 139 | "k(\"a+=1\")\n", 140 | "k('a')" 141 | ] 142 | }, 143 | { 144 | "cell_type": "markdown", 145 | "metadata": {}, 146 | "source": [ 147 | "Multi-line inputs are supported. If the last line is an expression, it is returned:" 148 | ] 149 | }, 150 | { 151 | "cell_type": "code", 152 | "execution_count": null, 153 | "metadata": {}, 154 | "outputs": [ 155 | { 156 | "data": { 157 | "text/plain": [ 158 | "namespace(foo=2)" 159 | ] 160 | }, 161 | "execution_count": null, 162 | "metadata": {}, 163 | "output_type": "execute_result" 164 | } 165 | ], 166 | "source": [ 167 | "k(\"\"\"import types\n", 168 | "b = types.SimpleNamespace(foo=a)\n", 169 | "b\"\"\")" 170 | ] 171 | }, 172 | { 173 | "cell_type": "markdown", 174 | "metadata": {}, 175 | "source": [ 176 | "The original source code is stored, so `inspect.getsource` works and, tracebacks have full details." 177 | ] 178 | }, 179 | { 180 | "cell_type": "code", 181 | "execution_count": null, 182 | "metadata": {}, 183 | "outputs": [ 184 | { 185 | "data": { 186 | "text/plain": [ 187 | "'def f(): pass # a comment\\n'" 188 | ] 189 | }, 190 | "execution_count": null, 191 | "metadata": {}, 192 | "output_type": "execute_result" 193 | } 194 | ], 195 | "source": [ 196 | "k(\"\"\"def f(): pass # a comment\n", 197 | "import inspect\n", 198 | "inspect.getsource(f)\"\"\")" 199 | ] 200 | }, 201 | { 202 | "cell_type": "markdown", 203 | "metadata": {}, 204 | "source": [ 205 | "When creating a `TinyKernel`, you can pass a dict of globals to initialize the environment:" 206 | ] 207 | }, 208 | { 209 | "cell_type": "code", 210 | "execution_count": null, 211 | "metadata": {}, 212 | "outputs": [ 213 | { 214 | "data": { 215 | "text/plain": [ 216 | "'barbar'" 217 | ] 218 | }, 219 | "execution_count": null, 220 | "metadata": {}, 221 | "output_type": "execute_result" 222 | } 223 | ], 224 | "source": [ 225 | "k = TinyKernel(glb={'foo':'bar'})\n", 226 | "k('foo*2')" 227 | ] 228 | }, 229 | { 230 | "cell_type": "markdown", 231 | "metadata": {}, 232 | "source": [ 233 | "Pass `name` to customize the string that appears in tracebacks (\"kernel\" by default):" 234 | ] 235 | }, 236 | { 237 | "cell_type": "code", 238 | "execution_count": null, 239 | "metadata": {}, 240 | "outputs": [], 241 | "source": [ 242 | "#hide\n", 243 | "import traceback" 244 | ] 245 | }, 246 | { 247 | "cell_type": "code", 248 | "execution_count": null, 249 | "metadata": {}, 250 | "outputs": [ 251 | { 252 | "name": "stdout", 253 | "output_type": "stream", 254 | "text": [ 255 | "Traceback (most recent call last):\n", 256 | " File \"\", line 5, in \n", 257 | " try: k(code)\n", 258 | " File \"/home/jhoward/git/tinykernel/tinykernel/__init__.py\", line 20, in __call__\n", 259 | " if expr: return self._run(Expression(expr.value), nm, 'eval')\n", 260 | " File \"/home/jhoward/git/tinykernel/tinykernel/__init__.py\", line 12, in _run\n", 261 | " def _run(self, p, nm, mode='exec'): return eval(compiler(p, nm, mode), self.glb)\n", 262 | " File \"\", line 3, in \n", 263 | " print(f())\n", 264 | " File \"\", line 2, in f\n", 265 | " return 1/0\n", 266 | "ZeroDivisionError: division by zero\n", 267 | "\n" 268 | ] 269 | } 270 | ], 271 | "source": [ 272 | "k = TinyKernel(name='myapp')\n", 273 | "code = '''def f():\n", 274 | " return 1/0\n", 275 | "print(f())'''\n", 276 | "try: k(code)\n", 277 | "except Exception as e: print(traceback.format_exc())" 278 | ] 279 | }, 280 | { 281 | "cell_type": "markdown", 282 | "metadata": {}, 283 | "source": [ 284 | "## Acknowledgements" 285 | ] 286 | }, 287 | { 288 | "cell_type": "markdown", 289 | "metadata": {}, 290 | "source": [ 291 | "Thanks to Christopher Prohm, Matthias Bussonnier, and Aaron Meurer for their helpful insights in [this twitter thread](https://twitter.com/jeremyphoward/status/1424990665746763781)." 292 | ] 293 | } 294 | ], 295 | "metadata": { 296 | "kernelspec": { 297 | "display_name": "Python 3", 298 | "language": "python", 299 | "name": "python3" 300 | } 301 | }, 302 | "nbformat": 4, 303 | "nbformat_minor": 2 304 | } 305 | -------------------------------------------------------------------------------- /settings.ini: -------------------------------------------------------------------------------- 1 | [DEFAULT] 2 | host = github 3 | lib_name = tinykernel 4 | user = fastai 5 | description = A minimal Python kernel so you can run Python in your Python 6 | keywords = embedded python fastai nbdev nbprocess ipython kernel 7 | author = Jeremy Howard 8 | author_email = j@fast.ai 9 | copyright = 2021 onwards, Jeremy Howard 10 | branch = master 11 | version = 0.0.3 12 | min_python = 3.6 13 | audience = Developers 14 | language = English 15 | custom_sidebar = False 16 | license = apache2 17 | status = 3 18 | nbs_path = . 19 | doc_path = docs 20 | recursive = False 21 | doc_host = https://fastai.github.io 22 | doc_baseurl = /tinykernel/ 23 | git_url = https://github.com/fastai/tinykernel/tree/master/ 24 | lib_path = tinykernel 25 | title = tinykernel 26 | 27 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from pkg_resources import parse_version 2 | from configparser import ConfigParser 3 | import setuptools 4 | assert parse_version(setuptools.__version__)>=parse_version('36.2') 5 | 6 | # note: all settings are in settings.ini; edit there, not here 7 | config = ConfigParser(delimiters=['=']) 8 | config.read('settings.ini') 9 | cfg = config['DEFAULT'] 10 | 11 | cfg_keys = 'version description keywords author author_email'.split() 12 | expected = cfg_keys + "lib_name user branch license status min_python audience language".split() 13 | for o in expected: assert o in cfg, "missing expected setting: {}".format(o) 14 | setup_cfg = {o:cfg[o] for o in cfg_keys} 15 | 16 | licenses = { 17 | 'apache2': ('Apache Software License 2.0','OSI Approved :: Apache Software License'), 18 | 'mit': ('MIT License', 'OSI Approved :: MIT License'), 19 | 'gpl2': ('GNU General Public License v2', 'OSI Approved :: GNU General Public License v2 (GPLv2)'), 20 | 'gpl3': ('GNU General Public License v3', 'OSI Approved :: GNU General Public License v3 (GPLv3)'), 21 | 'bsd3': ('BSD License', 'OSI Approved :: BSD License'), 22 | } 23 | statuses = [ '1 - Planning', '2 - Pre-Alpha', '3 - Alpha', 24 | '4 - Beta', '5 - Production/Stable', '6 - Mature', '7 - Inactive' ] 25 | py_versions = '2.0 2.1 2.2 2.3 2.4 2.5 2.6 2.7 3.0 3.1 3.2 3.3 3.4 3.5 3.6 3.7 3.8'.split() 26 | 27 | requirements = cfg.get('requirements','').split() 28 | min_python = cfg['min_python'] 29 | lic = licenses.get(cfg['license'].lower(), (cfg['license'], None)) 30 | 31 | setuptools.setup( 32 | name = cfg['lib_name'], 33 | license = lic[0], 34 | classifiers = [ 35 | 'Development Status :: ' + statuses[int(cfg['status'])], 36 | 'Intended Audience :: ' + cfg['audience'].title(), 37 | 'Natural Language :: ' + cfg['language'].title(), 38 | ] + ['Programming Language :: Python :: '+o for o in py_versions[py_versions.index(min_python):]] + (['License :: ' + lic[1] ] if lic[1] else []), 39 | url = cfg['git_url'], 40 | packages = setuptools.find_packages(), 41 | include_package_data = True, 42 | install_requires = requirements, 43 | dependency_links = cfg.get('dep_links','').split(), 44 | python_requires = '>=' + cfg['min_python'], 45 | long_description = open('README.md').read(), 46 | long_description_content_type = 'text/markdown', 47 | zip_safe = False, 48 | entry_points = { 'console_scripts': cfg.get('console_scripts','').split() }, 49 | **setup_cfg) 50 | 51 | -------------------------------------------------------------------------------- /tinykernel/__init__.py: -------------------------------------------------------------------------------- 1 | __version__ = "0.0.3" 2 | __all__ = ['TinyKernel'] 3 | 4 | from ast import parse,Expr,Expression,Module 5 | from .compilerop import CachingCompiler 6 | 7 | compiler = CachingCompiler() 8 | 9 | class TinyKernel: 10 | "A tiny persistent kernel for Python code" 11 | def __init__(self, name='kernel', glb=None): 12 | self.glb = {'__name__':'tinykernel', '__package__':__package__} 13 | self.name,self.idx,self.glb = name,-1,glb or {'__name__':'tinykernel'} 14 | 15 | def _run(self, p, nm, mode='exec'): 16 | return eval(compiler(p, nm, mode), self.glb) 17 | 18 | def __call__(self, code): 19 | nm = compiler.cache(code, self.idx, prefix=self.name) 20 | self.idx += 1 21 | p = parse(code, filename=nm) if not isinstance(code, Module) else code 22 | expr = p.body.pop() if p.body and isinstance(p.body[-1], Expr) else None 23 | self._run(p, nm) 24 | if expr: return self._run(Expression(expr.value), nm, 'eval') 25 | 26 | -------------------------------------------------------------------------------- /tinykernel/_nbdev.py: -------------------------------------------------------------------------------- 1 | # AUTOGENERATED BY NBDEV! DO NOT EDIT! 2 | 3 | __all__ = ["index", "modules", "custom_doc_links", "git_url"] 4 | 5 | index = {} 6 | 7 | modules = [] 8 | 9 | doc_url = "https://fastai.github.io/tinykernel/" 10 | 11 | git_url = "https://github.com/fastai/tinykernel/tree/master/" 12 | 13 | def custom_doc_links(name): return None 14 | -------------------------------------------------------------------------------- /tinykernel/compilerop.py: -------------------------------------------------------------------------------- 1 | """Compiler tools with improved interactive support. From IPython. 2 | 3 | Provides compilation machinery similar to codeop, but with caching support so 4 | we can provide interactive tracebacks. 5 | 6 | Authors 7 | ------- 8 | * Robert Kern 9 | * Fernando Perez 10 | * Thomas Kluyver 11 | * Minor modifications for tinykernel by Jeremy Howard 12 | """ 13 | 14 | # Note: though it might be more natural to name this module 'compiler', that 15 | # name is in the stdlib and name collisions with the stdlib tend to produce 16 | # weird problems (often with third-party tools). 17 | 18 | #----------------------------------------------------------------------------- 19 | # Copyright (C) 2010-2011 The IPython Development Team. 20 | # tinykernel modifications (C) 2021 onwards Jeremy Howard. 21 | # 22 | # Distributed under the terms of the Apache 2 License. 23 | # 24 | # The full license is in the file LICENSE, distributed with this software. 25 | #----------------------------------------------------------------------------- 26 | 27 | #----------------------------------------------------------------------------- 28 | # Imports 29 | #----------------------------------------------------------------------------- 30 | 31 | # Stdlib imports 32 | import __future__ 33 | from ast import PyCF_ONLY_AST 34 | import codeop 35 | import functools 36 | import hashlib 37 | import linecache 38 | import operator 39 | import time 40 | from contextlib import contextmanager 41 | 42 | #----------------------------------------------------------------------------- 43 | # Constants 44 | #----------------------------------------------------------------------------- 45 | 46 | # Roughly equal to PyCF_MASK | PyCF_MASK_OBSOLETE as defined in pythonrun.h, 47 | # this is used as a bitmask to extract future-related code flags. 48 | PyCF_MASK = functools.reduce(operator.or_, 49 | (getattr(__future__, fname).compiler_flag 50 | for fname in __future__.all_feature_names)) 51 | 52 | #----------------------------------------------------------------------------- 53 | # Local utilities 54 | #----------------------------------------------------------------------------- 55 | 56 | def code_name(code, number=0, prefix='ipython'): 57 | """ Compute a (probably) unique name for code for caching. 58 | 59 | This now expects code to be unicode. 60 | """ 61 | hash_digest = hashlib.sha1(code.encode("utf-8")).hexdigest() 62 | # Include the number and 12 characters of the hash in the name. It's 63 | # pretty much impossible that in a single session we'll have collisions 64 | # even with truncated hashes, and the full one makes tracebacks too long 65 | return '<{2}-{0}-{1}>'.format(number, hash_digest[:12], prefix) 66 | 67 | #----------------------------------------------------------------------------- 68 | # Classes and functions 69 | #----------------------------------------------------------------------------- 70 | 71 | class CachingCompiler(codeop.Compile): 72 | """A compiler that caches code compiled from interactive statements. 73 | """ 74 | 75 | def __init__(self): 76 | codeop.Compile.__init__(self) 77 | 78 | # This is ugly, but it must be done this way to allow multiple 79 | # simultaneous ipython instances to coexist. Since Python itself 80 | # directly accesses the data structures in the linecache module, and 81 | # the cache therein is global, we must work with that data structure. 82 | # We must hold a reference to the original checkcache routine and call 83 | # that in our own check_cache() below, but the special IPython cache 84 | # must also be shared by all IPython instances. If we were to hold 85 | # separate caches (one in each CachingCompiler instance), any call made 86 | # by Python itself to linecache.checkcache() would obliterate the 87 | # cached data from the other IPython instances. 88 | if not hasattr(linecache, '_ipython_cache'): 89 | linecache._ipython_cache = {} 90 | if not hasattr(linecache, '_checkcache_ori'): 91 | linecache._checkcache_ori = linecache.checkcache 92 | # Now, we must monkeypatch the linecache directly so that parts of the 93 | # stdlib that call it outside our control go through our codepath 94 | # (otherwise we'd lose our tracebacks). 95 | linecache.checkcache = check_linecache_ipython 96 | 97 | 98 | def ast_parse(self, source, filename='', symbol='exec'): 99 | """Parse code to an AST with the current compiler flags active. 100 | 101 | Arguments are exactly the same as ast.parse (in the standard library), 102 | and are passed to the built-in compile function.""" 103 | return compile(source, filename, symbol, self.flags | PyCF_ONLY_AST, 1) 104 | 105 | def reset_compiler_flags(self): 106 | """Reset compiler flags to default state.""" 107 | # This value is copied from codeop.Compile.__init__, so if that ever 108 | # changes, it will need to be updated. 109 | self.flags = codeop.PyCF_DONT_IMPLY_DEDENT 110 | 111 | @property 112 | def compiler_flags(self): 113 | """Flags currently active in the compilation process. 114 | """ 115 | return self.flags 116 | 117 | def cache(self, transformed_code, number=0, raw_code=None, prefix='ipython'): 118 | """Make a name for a block of code, and cache the code. 119 | 120 | Parameters 121 | ---------- 122 | transformed_code : str 123 | The executable Python source code to cache and compile. 124 | number : int 125 | A number which forms part of the code's name. Used for the execution 126 | counter. 127 | raw_code : str 128 | The raw code before transformation, if None, set to `transformed_code`. 129 | 130 | Returns 131 | ------- 132 | The name of the cached code (as a string). Pass this as the filename 133 | argument to compilation, so that tracebacks are correctly hooked up. 134 | """ 135 | if raw_code is None: 136 | raw_code = transformed_code 137 | 138 | name = code_name(transformed_code, number, prefix=prefix) 139 | entry = ( 140 | len(transformed_code), 141 | time.time(), 142 | [line + "\n" for line in transformed_code.splitlines()], 143 | name, 144 | ) 145 | linecache.cache[name] = entry 146 | linecache._ipython_cache[name] = entry 147 | return name 148 | 149 | @contextmanager 150 | def extra_flags(self, flags): 151 | ## bits that we'll set to 1 152 | turn_on_bits = ~self.flags & flags 153 | 154 | 155 | self.flags = self.flags | flags 156 | try: 157 | yield 158 | finally: 159 | # turn off only the bits we turned on so that something like 160 | # __future__ that set flags stays. 161 | self.flags &= ~turn_on_bits 162 | 163 | 164 | def check_linecache_ipython(*args): 165 | """Call linecache.checkcache() safely protecting our cached values. 166 | """ 167 | # First call the original checkcache as intended 168 | linecache._checkcache_ori(*args) 169 | # Then, update back the cache with our data, so that tracebacks related 170 | # to our compiled codes can be produced. 171 | linecache.cache.update(linecache._ipython_cache) 172 | 173 | --------------------------------------------------------------------------------