Funchacks - Fun module which is a small set of utilities

Overview

funchacks

PyPI version Supported python versions
CI status Mypy badge

👋 Introduction

Funchacks is a fun module that provides a small package of utilities.

Dynamic signature change without compile, eval and exec? That was the main idea of the project! But this path is a little dangerous, so the part could not be implemented, but if possible it will be implemented in the next versions!

So is it worth using funchacks signature utilities? More likely no than yes. If you want a really optimized and safe implementation of this idea, it's better to look into makefun (this was another reason why I wanted to do a dynamic signature change without compile, eval and exec).

⚙️ Installation

pip install funchacks

🚀 Quick start

  • 🔎 Function locals

from funchacks import inspections


def foo() -> None:
    some_local_var = 1
    other_var = 2

>>> dict(inspections.getlocals(foo.__code__))
{"some_local_var": 1, "other_var": 2}
  • 🔗 Dynamic function signature

(!) Note: if you add positional only or positional arguments, then there must be *args in the function signature. Accordingly, if you add keyword only or keyword arguments - **kwargs.

import inspect
from typing import Any

from funchacks import sig
@sig.change_args(
    sig.posonly("first"),
    sig.arg("second"),
)
def foo(*args: Any) -> None:
    """
    !!! Note:
        Temporarily positional only arguments are available only for
        the signature, there may be errors when calling the function.
    """

>>> inspect.Signature.from_callable(foo)
(first, /, second, *args)
@sig.change_args(
    sig.kwarg("first", None),
    sig.kwonly("second"),
)
def bar(**kwargs: Any) -> None:
    """
    !!! Note:
        Temporarily keyword only arguments are available only for
        the signature, there may be errors when calling the function.
    """

>>> inspect.Signature.from_callable(bar)
(first=None, *, second, **kwargs)
@sig.change_args(
    sig.arg("first"),
    sig.kwarg("second", None)
)
def baz(*args: Any, **kwargs: Any) -> None:
    """This should work.

    But how to access the arguments? locals?...
    """
    # All wrapped function has __sig__ attribute
    # that contains function signature.
    lvars = sig.Bind.from_locals(locals(), in_=baz)

    assert lvars.args() == ["first"]
    assert lvars.kwargs() == ["second"]

    return lvars.get("first") + lvars.get("second")

>>> inspect.Signature.from_callable(baz)
(first, second=None, *args, **kwargs)

>>> baz(1, 2)
3

Signature from function.

def spam(a, /, b, c=None, *, d) -> None:
    pass


@sig.from_function(spam)
def eggs(*args: Any, **kwargs: Any) -> None:
    pass

>>> inspect.Signature.from_callable(eggs)
(a, /, b, c=None, *, d)

Making small wrap.

from types import CodeType

from funchacks import make_wrap, WrapFunction


def foo() -> None:
    some_local = 1
    other_local = 2

wrap = make_wrap(foo)
wrap_from_func = WrapFunction.from_function(foo)

>>> dict(wrap.flocals)
{'some_local': 1, 'other_local': 2}
>>> isinstance(wrap, WrapFunction)
True
>>> dict(wrap.flocals) == dict(wrap_from_func.flocals)
True
>>> isinstance(wrap.code, CodeType)
True
You might also like...
Make creating Excel XLSX files fun again
Make creating Excel XLSX files fun again

Poi: Make creating Excel XLSX files fun again. Poi helps you write Excel sheet in a declarative way, ensuring you have a better Excel writing experien

Wordle is fun, so let's ruin it with computers.

ruin-wordle Wordle is fun, so let's ruin it with computers. Metrics This repository assesses two metrics about each algorithm: Success: how many of th

Moji sends text and fun facts from different APIs wit da use of a notification deamon
Moji sends text and fun facts from different APIs wit da use of a notification deamon

Moji sends text and fun facts from different APIs wit da use of a notification deamon. Can be runned via dmenu or rofi.

Just messing around with AI for fun coding 😂

Python-AI Projects 🤖 World Clock ⏰ ⚙︎ Steps to run world-clock.py file Download and open the file in your Python IDE. Run the file a type the name of

Its a simple and fun to use application. You can make your own quizes and send the lik of the quiz to your friends.
Its a simple and fun to use application. You can make your own quizes and send the lik of the quiz to your friends.

Quiz Application Its a simple and fun to use application. You can make your own quizes and send the lik of the quiz to your friends. When they would a

Cross-platform config and manager for click console utilities.

climan Help the project financially: Donate: https://smartlegion.github.io/donate/ Yandex Money: https://yoomoney.ru/to/4100115206129186 PayPal: https

python DroneCAN code generation, interface and utilities

UAVCAN v0 stack in Python Python implementation of the UAVCAN v0 protocol stack. UAVCAN is a lightweight protocol designed for reliable communication

Aerospace utilities: flight conditions package, standard atmosphere model, and more.

Aerospace Utilities About Module that contains commonly-used aerospace utilities for problem solving. Flight Condition: input altitude to compute comm

LinuxHelper - A collection of utilities for non-technical Linux users accessible via a GUI

Linux Helper A collection of utilities for non-technical Linux users accessible via a GUI This app is still in very early development, expect bugs and

Releases(funchacks)
Owner
DenyS
My discord: DenyS#1469
DenyS
Tutorials on advanced python topics, and literate programming framework to write them.

Advanced course on Python3 This course covers several topics Python decorators The python object system / meta classes Also see my text on Python impo

Michael Moser 59 Dec 19, 2022
Konomi: Kind and Optimized Next brOadcast watching systeM Infrastructure

Konomi 備考・注意事項 現在 α 版で、まだ実験的なプロダクトです。通常利用には耐えないでしょうし、サポートもできません。 安定しているとは到底言いがたい品質ですが、それでも構わない方のみ導入してください。 使い方などの説明も用意できていないため、自力でトラブルに対処できるエンジニアの方以外に

tsukumi 243 Dec 30, 2022
sumCulator Это калькулятор, который умеет складывать 2 числа.

sumCulator Это калькулятор, который умеет складывать 2 числа. Но есть условия: Эти 2 числа не могут быть отрицательными (всё-таки это вычитание, а не

0 Jul 12, 2022
Broken Link Finder is a Burp Extension to detect broken links for a passive scanning domains and links.

Broken Link Finder Broken Link Finder is a Burp Extension to detect broken links for a passive scanning domains and links. Inspired by InitRoot's link

Red Section 10 Sep 11, 2021
Modern API wrapper for Genshin Impact built on asyncio and pydantic.

genshin.py Modern API wrapper for Genshin Impact built on asyncio and pydantic.

sadru 212 Jan 06, 2023
An event-based script that is designed to improve your aim

Aim-Trainer Info: This is an event-based script that is designed to improve a user's aim. It was built using Python Turtle and the Random library. Ins

Ethan Francolla 4 Feb 17, 2022
Display your data in an attractive way in your notebook!

Bloxs Bloxs is a simple python package that helps you display information in an attractive way (formed in blocks). Perfect for building dashboards, re

MLJAR 192 Dec 28, 2022
Nuclei - Burp Extension allows to run nuclei scanner directly from burp and transforms json results into the issues

Nuclei - Burp Extension Simple extension that allows to run nuclei scanner directly from burp and transforms json results into the issues. Installatio

106 Dec 22, 2022
A web application which you can search, buy or sell shares with current prices which provided by IEX.

CS50 - Stock Exchange A web application which you can search, buy or sell shares with current prices which provided by IEX. Table of Contents Setup St

1 May 28, 2022
A simple wrapper for joy library

Joy CodeGround A simple wrapper for joy library to render joy sketches in browser using vs code, (or in other words, for those who are allergic to Jup

rijfas 9 Sep 08, 2022
BridgeWalk is a partially-observed reinforcement learning environment with dynamics of varying stochasticity.

BridgeWalk is a partially-observed reinforcement learning environment with dynamics of varying stochasticity. The player needs to walk along a bridge to reach a goal location. When the player walks o

Danijar Hafner 6 Jun 13, 2022
Password manager using MySQL and Python 3.10.2

Password Manager Password manager using MySQL and Python 3.10.2 Installation Install my-project with github git clone https://github.com/AyaanSiddiq

1 Feb 18, 2022
Pyjiting is a experimental Python-JIT compiler, which is the product of my undergraduate thesis

Pyjiting is a experimental Python-JIT compiler, which is the product of my undergraduate thesis. The goal is to implement a light-weight miniature general-purpose Python JIT compiler.

Lance.Moe 10 Apr 17, 2022
Larvamatch - Find your larva or punk match.

LarvaMatch Find your larva or punk match. UI TBD API (not started) The API will allow you to specify a punk by token id to find a larva match, and vic

1 Jan 02, 2022
Encode stuff with ducks!

Duckify Encoder Usage Download main.py and run it. main.py has an encoded version in encoded_main.py.txt. As A Module Download the duckify folder (or

Jeremiah 2 Nov 15, 2021
A pairs trade is a market neutral trading strategy enabling traders to profit from virtually any market conditions.

A pairs trade is a market neutral trading strategy enabling traders to profit from virtually any market conditions. This strategy is categorized as a statistical arbitrage and convergence trading str

Kanupriya Anand 13 Nov 27, 2022
A python package to manage the stored receiver-side Strain Green's Tensor (SGT) database of 3D background models and able to generate Green's function and synthetic waveform

A python package to manage the stored receiver-side Strain Green's Tensor (SGT) database of 3D background models and able to generate Green's function and synthetic waveform

Liang Ding 7 Dec 14, 2022
tox-gh is a tox plugin which helps running tox on GitHub Actions with multiple different Python versions on multiple workers in parallel

tox-gh is a tox plugin which helps running tox on GitHub Actions with multiple different Python versions on multiple workers in parallel. This project is inspired by tox-travis.

tox development team 19 Dec 26, 2022
NasaApod - Astronomy Picture of the Day

Astronomy Picture of the Day Get interesting Astronomical pictures with a brief

Shripad Rao 1 Feb 15, 2022
InfiniPy has some neat features - like the endpoint for function

InfiniPy has some neat features - like the endpoint for function

ZeroTwo 7 Nov 20, 2022