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
A Classroom Engagement Platform

Project Introduction This is project introduction Setup Setting up Postgres This is the most tricky part when setting up the application. You will nee

Santosh Kumar Patro 1 Nov 18, 2021
Python / C++ based particle reaction-diffusion simulator

ReaDDy (Reaction Diffusion Dynamics) is an open source particle based reaction-diffusion simulator that can be configured and run via Python. Currentl

ReaDDy 46 Dec 09, 2022
An kind of operating system portal to a variety of apps with pure python

pyos An kind of operating system portal to a variety of apps. Installation Run this on your terminal: git clone https://github.com/arjunj132/pyos.git

1 Jan 22, 2022
Hopefully it'll become a very annoying desktop pet

AnnoyingPet Basic Tutorial: https://seebass22.github.io/python-desktop-pet-tutorial/ Handling Mouse Input: https://pythonhosted.org/pynput/mouse.html

1 Jun 08, 2022
LibreMind is a free meditation app made in under 24 hours. It has various meditation, breathwork, and visualization exercises.

libreMind Meditation exercises What is it? LibreMind is a free meditation app made in under 24 hours. It has various meditation, breathwork, and visua

1 May 24, 2022
A simple script for generating screenshots with Vapoursynth

Vapoursynth-Screenshots A simple script for generating screenshots with Vapoursynth. About I'm lazy, and hate changing variables for each batch of scr

7 Dec 31, 2022
A set of tools for ripping music from Konami mobile games

Konami Mobile Ripping Toolset A set of tools for ripping music from Konami mobile games Contents nigger.py for niggering konami's website, ripping all

5 Oct 20, 2022
Izy - Python functions and classes that make python even easier than it is

izy Python functions and classes that make it even easier! You will wonder why t

5 Jul 04, 2022
Proyecto - Análisis de texto de eventos históricos

Acceder al código desde Google Colab para poder ver de manera adecuada todas las visualizaciones y poder interactuar con ellas. Link de acceso: https:

1 Jan 31, 2022
token vesting escrow with cliff and clawback

Yearn Vesting Escrow A modified version of Curve Vesting Escrow contracts with added functionality: An escrow can have a start_date in the past.

62 Dec 08, 2022
DOP-Tuning(Domain-Oriented Prefix-tuning model)

DOP-Tuning DOP-Tuning(Domain-Oriented Prefix-tuning model)代码基于Prefix-Tuning改进. Files ├── seq2seq # Code for encoder-decoder arch

Andrew Zeng 5 Nov 02, 2022
An optional component handler for hikari, inspired by discord.py's views.

hikari-miru An optional component handler for hikari, inspired by discord.py's views.

43 Dec 26, 2022
Neogex is a human readable parser standard, being implemented in Python

Neogex (New Expressions) Parsing Standard Much like Regex, Neogex allows for string parsing and validation based on a set of requirements. Unlike Rege

Seamus Donnellan 1 Dec 17, 2021
Density is a open-sourced multi-purpose tool for ROBLOX with some cool

Density is a open-sourced multi-purpose tool for ROBLOX with some cool

ssl 5 Jul 16, 2022
Игра реализована с помощью языке python3.9, библиотеки pygame

Игра в танки Игра реализована с помощью языке python3.9, библиотеки pygame. Игра имеет несколько уровней. Правила: есть танки, которые стреляют, есть

1 Jan 01, 2022
Repository voor verhalen over de woningbouw-opgave in Nederland

Analyse plancapaciteit woningen In deze notebook zetten we cijfers op een rij om de woningbouwplannen van Nederlandse gemeenten in kaart te kunnen bre

Follow the Money 10 Jun 30, 2022
TMTC Commander Core

This commander application was first developed by KSat for the SOURCE project to test the on-board software but has evolved into a more generic tool for satellite developers to perform TMTC (Telemetr

robamu 8 Dec 14, 2022
GibMacOS - Py2/py3 script that can download macOS components direct from Apple

Py2/py3 script that can download macOS components direct from Apple Can also now build Internet Recovery USB installers from Windows using dd and 7zip

CorpNewt 4.8k Jan 02, 2023
Blender addon that simplifies access to useful operators and adds missing functionality

Quick Menu is a Blender addon that simplifies common tasks Compatible with Blender 3.x.x Install through Edit - Preferences - Addons - Install... -

passivestar 94 Dec 27, 2022
A Python script made for the Python Discord Pixels event.

Python Discord Pixels A Python script made for the Python Discord Pixels event. Usage Create an image.png RGBA image with your pattern. Transparent pi

Stanisław Jelnicki 4 Mar 23, 2022