mainpy 1.4.0

Creator: bradpython12

Last updated:

Add to Cart

Description:

mainpy 1.4.0

@main.py



























Basic Examples
With mainpy, there's no need to write if __name__ == '__main__' the
boilerplate anymore:


without mainpy
with mainpy



if __name__ == '__main__':
app()

def app(): ...



from mainpy import main

@main
def app(): ...




For async apps, the improvement becomes even more obvious:


without mainpy
with mainpy



import asyncio

async def async_app(): ...

if __name__ == '__main__':
with asyncio.Runner() as runner:
runner.run(async_app())



from mainpy import main

@main
async def async_app(): ...




External Libraries
Even though mainpy requires no other dependencies than typing_extensions
(on Python < 3.10), it has optional support for uvloop, and plays
nicely with popular CLI libraries, e.g. click and typer.
uvloop
If you have uvloop installed, mainpy will automatically call
uvloop.install() before running your async main function.
This can be disabled by setting use_uvloop=False, e.g.:
@main(use_uvloop=False)
async def app(): ...

Click
With click you can simply add the decorator as usual.

[!IMPORTANT]
The @mainpy.main decorator must come before @click.command().

import mainpy
import click

@mainpy.main
@click.command()
def click_command():
click.echo('Hello from click_command')

The function that is decorated with @mainpy.main is executed immediately.
But a @click.group must be defined before the command function.
In this case, mainpy.main should be called after all has been setup:
import mainpy
import click

@click.group()
def group(): ...

@group.command()
def command(): ...

mainpy.main(group)

Typer
A typer internally does some initialization after a command
has been defined.
Instead of using @mainpy.main on the command itself, you should use
mainpy.main() manually:
import mainpy
import typer

app = typer.Typer()

@app.command()
def command():
typer.echo('typer.Typer()')

mainpy.main(command)

Debug mode
Optionally, Python's development mode can be emulated by passing
debug=True to mainpy.main. This does three things:

Enable the faulthandler
Configure warnings to display all warnings
Runs async functions in debug mode

@main(debug=True)
def app(): ...

Installation
The mainpy package is available on pypi for Python ≥3.8:
pip install mainpy

Additionally, you can install the uvloop extra which will install
uvloop>=0.14 (unless you're on windows):
pip install mainpy[uvloop]

License

For personal and professional use. You cannot resell or redistribute these repositories in their original state.

Customer Reviews

There are no reviews.