tinykernel - A minimal Python kernel so you can run Python in your Python

Overview

tinykernel

A minimal Python kernel, so you can run Python in your Python.

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.

Install

With pip:

pip install tinykernel

With conda:

conda install -c fastai tinykernel

How to use

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

k = TinyKernel()

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

k("a=1")

Expressions return the value of the expression:

k('a')
1

All variables are persisted across calls:

k("a+=1")
k('a')
2

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

k("""import types
b = types.SimpleNamespace(foo=a)
b""")
namespace(foo=2)

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

k("""def f(): pass # a comment
import inspect
inspect.getsource(f)""")
'def f(): pass # a comment\n'

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

k = TinyKernel(glb={'foo':'bar'})
k('foo*2')
'barbar'

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

k = TinyKernel(name='myapp')
code = '''def f():
    return 1/0
print(f())'''
try: k(code)
except Exception as e: print(traceback.format_exc())
", line 5, in try: k(code) File "/home/jhoward/git/tinykernel/tinykernel/__init__.py", line 20, in __call__ if expr: return self._run(Expression(expr.value), nm, 'eval') File "/home/jhoward/git/tinykernel/tinykernel/__init__.py", line 12, in _run def _run(self, p, nm, mode='exec'): return eval(compiler(p, nm, mode), self.glb) File "", line 3, in print(f()) File "", line 2, in f return 1/0 ZeroDivisionError: division by zero ">
Traceback (most recent call last):
  File "", line 5, in 
    try: k(code)
  File "/home/jhoward/git/tinykernel/tinykernel/__init__.py", line 20, in __call__
    if expr: return self._run(Expression(expr.value), nm, 'eval')
  File "/home/jhoward/git/tinykernel/tinykernel/__init__.py", line 12, in _run
    def _run(self, p, nm, mode='exec'): return eval(compiler(p, nm, mode), self.glb)
  File "", line 3, in 
    print(f())
  File "", line 2, in f
    return 1/0
ZeroDivisionError: division by zero

Acknowledgements

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

You might also like...
Exploring Image Deblurring via Blur Kernel Space (CVPR'21)
Exploring Image Deblurring via Blur Kernel Space (CVPR'21)

Exploring Image Deblurring via Encoded Blur Kernel Space About the project We introduce a method to encode the blur operators of an arbitrary dataset

Official PyTorch code for Mutual Affine Network for Spatially Variant Kernel Estimation in Blind Image Super-Resolution (MANet, ICCV2021)
Official PyTorch code for Mutual Affine Network for Spatially Variant Kernel Estimation in Blind Image Super-Resolution (MANet, ICCV2021)

Mutual Affine Network for Spatially Variant Kernel Estimation in Blind Image Super-Resolution (MANet, ICCV2021) This repository is the official PyTorc

[ICCV 2021] Official Tensorflow Implementation for
[ICCV 2021] Official Tensorflow Implementation for "Single Image Defocus Deblurring Using Kernel-Sharing Parallel Atrous Convolutions"

KPAC: Kernel-Sharing Parallel Atrous Convolutional block This repository contains the official Tensorflow implementation of the following paper: Singl

The code for the NSDI'21 paper "BMC: Accelerating Memcached using Safe In-kernel Caching and Pre-stack Processing".

BMC The code for the NSDI'21 paper "BMC: Accelerating Memcached using Safe In-kernel Caching and Pre-stack Processing". BibTex entry available here. B

Fuzzing the Kernel Using Unicornafl and AFL++
Fuzzing the Kernel Using Unicornafl and AFL++

Unicorefuzz Fuzzing the Kernel using UnicornAFL and AFL++. For details, skim through the WOOT paper or watch this talk at CCCamp19. Is it any good? ye

A Kernel fuzzer focusing on race bugs

Razzer: Finding kernel race bugs through fuzzing Environment setup $ source scripts/envsetup.sh scripts/envsetup.sh sets up necessary environment var

Fuzzer for Linux Kernel Drivers

difuze: Fuzzer for Linux Kernel Drivers This repo contains all the sources (including setup scripts), you need to get difuze up and running. Tested on

Skyformer: Remodel Self-Attention with Gaussian Kernel and Nystr\
Skyformer: Remodel Self-Attention with Gaussian Kernel and Nystr\"om Method (NeurIPS 2021)

Skyformer This repository is the official implementation of Skyformer: Remodel Self-Attention with Gaussian Kernel and Nystr"om Method (NeurIPS 2021).

Vertical Federated Principal Component Analysis and Its Kernel Extension on Feature-wise Distributed Data based on Pytorch Framework
Vertical Federated Principal Component Analysis and Its Kernel Extension on Feature-wise Distributed Data based on Pytorch Framework

VFedPCA+VFedAKPCA This is the official source code for the Paper: Vertical Federated Principal Component Analysis and Its Kernel Extension on Feature-

Releases(0.0.2)
Minimal diffusion models - Minimal code and simple experiments to play with Denoising Diffusion Probabilistic Models (DDPMs)

Minimal code and simple experiments to play with Denoising Diffusion Probabilist

Rithesh Kumar 16 Oct 6, 2022
A minimal solution to hand motion capture from a single color camera at over 100fps. Easy to use, plug to run.

Minimal Hand A minimal solution to hand motion capture from a single color camera at over 100fps. Easy to use, plug to run. This project provides the

Yuxiao Zhou 824 Jan 7, 2023
Spam your friends and famly and when you do your famly will disown you and you will have no friends.

SpamBot9000 Spam your friends and family and when you do your family will disown you and you will have no friends. Terms of Use Disclaimer: Please onl

DJ15 0 Jun 9, 2022
Checkout some cool self-projects you can try your hands on to curb your boredom this December!

SoC-Winter Checkout some cool self-projects you can try your hands on to curb your boredom this December! These are short projects that you can do you

Web and Coding Club, IIT Bombay 29 Nov 8, 2022
A hand tracking demo made with mediapipe where you can control lights with pinching your fingers and moving your hand up/down.

HandTrackingBrightnessControl A hand tracking demo made with mediapipe where you can control lights with pinching your fingers and moving your hand up

Teemu Laurila 19 Feb 12, 2022
Code for Mesh Convolution Using a Learned Kernel Basis

Mesh Convolution This repository contains the implementation (in PyTorch) of the paper FULLY CONVOLUTIONAL MESH AUTOENCODER USING EFFICIENT SPATIALLY

Yi_Zhou 35 Jan 3, 2023
(CVPR 2021) PAConv: Position Adaptive Convolution with Dynamic Kernel Assembling on Point Clouds

PAConv: Position Adaptive Convolution with Dynamic Kernel Assembling on Point Clouds by Mutian Xu*, Runyu Ding*, Hengshuang Zhao, and Xiaojuan Qi. Int

CVMI Lab 228 Dec 25, 2022
Official PyTorch code for CVPR 2020 paper "Deep Active Learning for Biased Datasets via Fisher Kernel Self-Supervision"

Deep Active Learning for Biased Datasets via Fisher Kernel Self-Supervision https://arxiv.org/abs/2003.00393 Abstract Active learning (AL) aims to min

Denis 29 Nov 21, 2022