Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
KOLANICH committed Oct 18, 2023
0 parents commit 641fd74
Show file tree
Hide file tree
Showing 14 changed files with 980 additions and 0 deletions.
12 changes: 12 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
root = true

[*]
charset = utf-8
indent_style = tab
indent_size = 4
insert_final_newline = true
end_of_line = lf

[*.{yml,yaml}]
indent_style = space
indent_size = 2
1 change: 1 addition & 0 deletions .github/.templateMarker
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
KOLANICH/python_project_boilerplate.py
8 changes: 8 additions & 0 deletions .github/dependabot.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
version: 2
updates:
- package-ecosystem: "pip"
directory: "/"
schedule:
interval: "daily"
allow:
- dependency-type: "all"
15 changes: 15 additions & 0 deletions .github/workflows/CI.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
name: CI
on:
push:
branches: [master]
pull_request:
branches: [master]

jobs:
build:
runs-on: ubuntu-22.04
steps:
- name: typical python workflow
uses: KOLANICH-GHActions/typical-python-workflow@master
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
10 changes: 10 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
__pycache__
*.py[co]
/*.egg-info
*.srctrlbm
*.srctrldb
build
dist
.eggs
monkeytype.sqlite3
/.ipynb_checkpoints
51 changes: 51 additions & 0 deletions .gitlab-ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
image: registry.gitlab.com/kolanich-subgroups/docker-images/fixed_python:latest

variables:
DOCKER_DRIVER: overlay2
SAST_ANALYZER_IMAGE_TAG: latest
SAST_DISABLE_DIND: "true"
SAST_CONFIDENCE_LEVEL: 5
CODECLIMATE_VERSION: latest

include:
- template: SAST.gitlab-ci.yml
- template: Code-Quality.gitlab-ci.yml
- template: License-Management.gitlab-ci.yml

build:
tags:
- shared
- linux
stage: build
variables:
GIT_DEPTH: "1"
PYTHONUSERBASE: ${CI_PROJECT_DIR}/python_user_packages

before_script:
- export PATH="$PATH:$PYTHONUSERBASE/bin" # don't move into `variables`
- apt-get update
# todo:
#- apt-get -y install
#- pip3 install --upgrade
#- python3 ./fix_python_modules_paths.py

script:
- python3 -m build -nw bdist_wheel
- mv ./dist/*.whl ./dist/bind-0.CI-py3-none-any.whl
- pip3 install --upgrade ./dist/*.whl
- coverage run --source=bind -m --branch pytest --junitxml=./rspec.xml ./tests/test.py
- coverage report -m
- coverage xml

coverage: "/^TOTAL(?:\\s+\\d+){4}\\s+(\\d+%).+/"

cache:
paths:
- $PYTHONUSERBASE

artifacts:
paths:
- dist
reports:
junit: ./rspec.xml
cobertura: ./coverage.xml
1 change: 1 addition & 0 deletions Code_Of_Conduct.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
No codes of conduct!
4 changes: 4 additions & 0 deletions MANIFEST.in
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
include UNLICENSE
include *.md
include tests
include .editorconfig
186 changes: 186 additions & 0 deletions ReadMe.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,186 @@
bind.py [![Unlicensed work](https://raw.githubusercontent.com/unlicense/unlicense.org/master/static/favicon.png)](https://unlicense.org/)
=======
~~[wheel (GHA via `nightly.link`)](https://nightly.link/KOLANICH-libs/bind.py/workflows/CI/master/bind-0.CI-py3-none-any.whl)~~
~~[![GitHub Actions](https://github.com/KOLANICH-libs/bind.py/workflows/CI/badge.svg)](https://github.com/KOLANICH-libs/bind.py/actions/)~~
![N∅ dependencies](https://shields.io/badge/-N∅_deps!-0F0)
[![Libraries.io Status](https://img.shields.io/librariesio/github/KOLANICH-libs/bind.py.svg)](https://libraries.io/github/KOLANICH-libs/bind.py)
[![Code style: antiflash](https://img.shields.io/badge/code%20style-antiflash-FFF.svg)](https://codeberg.org/KOLANICH-tools/antiflash.py)

This is a tool to allow you to inline constants into functions for fun and profit. In some cases using this tool can give 30% gain of speed. In some, but not in the all ones - [in some cases it actually causes slowdown](https://codeberg.org/KOLANICH/bind.py/issues/4).


How does it work?
-----------------
It just
* moves some closured and global variables into constants, taking attention to arguments
* replaces "LOAD_DEREF" and "LOAD_GLOBAL" opcodes with "LOAD_CONST"
* removes moved variables from function ```__closure__``` property

Limitations
-----------
* When you define a function, sometimes it uses "LOAD_FAST" opcode to load. For now this case is not taken in account.
* Inlined variables shouldn't be modified because they are marked as constants. Doing this can cause undefined behavior including crashes of interpreter and SIGSEGVs. Adding support for these will require some analysis of control and data flow to check if a variable is modified, spawning a local variable and loading const there. For now the function doesn't check any of such kind of usage, it's your responsibility as a programmer to guarantee this.
* You should inspect bytecode (for example using ```dis```) of the func you want to optimize to understand if ```inline``` could help. If there is no ```LOAD_DEREF``` and ```LOAD_GLOBAL``` opcodes in a function it won't help in the current state.
* It doesn't modify functions' text, only bytecode. So source-code showing tools like ```??``` of IPython won't give accurate information.
* Python can optimize some inlined functions better than this tool, for example
```python
def a():
return 2+3
```
in fact loads not 2 and 3 but a precomputed 5, it will have 2 instructions smaller byte-code than
```python
@bind(x=2, y=3)
def a():
return x+y
```
* Inlining limits hackability. When a variable is inlined it cannot be monkey-patched easily by third-party code.
* This is very beta for now. For now it even breaks itself when inlined. Use it on small functions where there is nothing to break.
* Bytecode is implementation detail of cpython. It can and will change unexpectidly. This will make this to break. It also can be different between implementations.

How to use
----------
* Import the ```bind``` function
```python
from bind import bind
```

* You can explicitly call the function, providing it the function to optimize and the dict of variables to bind.
```python
c=1
def a(a, b):
print(a+c, b+d)
a=bind(a, {"c":c, "d":1})
a(1, 2) # 2 3
```
* You can use it as a decorator
```python
c=1
@bind({"c":c, "d":1})
@bind(c=c, d=1) #kwargs-syntax also works
def a(a, b):
print(a+c, b+d)
a(1, 2) # 2 3
```
* When used as decorator, you can also use kwargs-syntax
```python
@bind(c=1, d=1)
def a(a, b):
print(a+c, b+d)
a(1, 2) # 2 3
```
* You can specify variables separately
```python
c=1
@bind(c=c)
@bind(d=1)
def a(a, b):
print(a+c, b+d)
a(1, 2) # 2 3
```
* Inlined variable doesn't depend on closure
```python
c=1
d=1
def a(a, b):
print(a+c, b+d)
a(1, 2) # 2 3
b=bind(a, {"c":c, "d":1})
d=4
c=4
a(1, 2) # 5 6
b(1, 2) # still 2 3 because c is inlined
```
* Independence on following inlines
```python
b=bind(b, {"c":3, "d":4})
b(1, 2) # still 2 3 because there is no c and d anymore in that func
```
* You can inline all the variables visible from the current scope.
```python
c=1
def a1():
c=2
def a():
print(c)
c=3
return a
def a2():
c=2
@bind
def a():
print(c)
c=3
return a
b=a1()
c=a2()
b() # 3
c() # 2
```


Benchmark results
-----------------
To run the benchmark run
```bash
python3 benchmarkGen.py | python3
```
this wil give you the results:
```javascript
{
"load_global": {
"orig": 45.899,
"inlined": 32.968,
"% faster": 30.347
},
"load_deref": {
"orig": 37.911,
"inlined": 32.022,
"% faster": 15.532
}
}
```
As we see, inlined synthetic functions are really 15-30% faster!


Use case
--------
Situation: you have met some library. You looked into it and saw shitcode.
```python
class B:
def b1(a):
print(1+a)
def b2(a):
print(2+a)
...
def b100500(a):
print(100500+a)
```.
You have have refactored this shit using
```python
def genBFuncs(lol="lol"):
for i in range(100500):
def b(a):
print(i+a)
b.__name__="b"+str(i)
yield b
```

Some folks will say
> It will slow down our lib!
As we know from the benchmark, they are right.

Here is the response:
```python
# you have a function "a" making a functions "b" for some library
def genBFuncs(lol="lol"):
for i in range(100500):
@bind(i=i)
def b(a):
print(i+a)
b.__name__="b"+str(i)
yield b
```

This will rewrite functions bytecode so it will be nearly identical to the original versions.
24 changes: 24 additions & 0 deletions UNLICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
This is free and unencumbered software released into the public domain.

Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.

In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

For more information, please refer to <https://unlicense.org/>
Loading

0 comments on commit 641fd74

Please sign in to comment.