Ergonomic option parser on top of dataclasses, inspired by structopt.

Related tags

Miscellaneousoppapi
Overview

oppapī

Ergonomic option parser on top of dataclasses, inspired by structopt.

Usage

from typing import Optional
from oppapi import from_args, oppapi

@oppapi
class Opt:
    """
    Option parser using oppapi
    """

    host: str
    """ This will be positional argument of type `str` """

    port: Optional[int] = 8000
    """ Optional argument will be option argument """

opt = from_args(Opt)
print(opt)

The code above generates such option parser that

  • Generates parser description from class's docstring
  • Generates argument description from field's docstring
  • A field will be a positional argument
  • An optional field will be an optional argument

See the parser help message:

$ python simple.py -h
usage: simple.py [-h] [-p PORT] host

Option parser using oppapi

positional arguments:
  host                  This will be positional argument of type `str`

optional arguments:
  -h, --help            show this help message and exit
  -p PORT, --port PORT  Optional argument will be option argument

Running the program deserializes the command line arguments into an object of the declared class.

$ python simple.py localhost -p 20000
Opt(host='localhost', port=20000)

Supported types

short/long

oppapi generates flag names automatically, but you can specify arbitrary short/long names.

from typing import Optional
from oppapi import from_args, oppapi, field

@oppapi
class Opt:
    host: Optional[str] = field(short="-n", long="--hostname")

enum

enum.Enum and enum.IntEnum will be an argument with choices parameter.

class Food(Enum):
    A = "Apple"
    B = "Beer"
    C = "Chocolate"

class Price(IntEnum):
    A = 10
    B = 20
    C = 30

@oppapi
class Opt:
    food: Food
    price: Optional[Price]

usage will be like this:

positional arguments:
  {Apple,Beer,Chocolate}

optional arguments:
  -h, --help            show this help message and exit
  -p {10,20,30}, --price {10,20,30}

oppapi converts the command line arguments back to Enum.

$ python choice.py Apple --price 20
Opt(food=<Food.A: 'Apple'>, price=<Price.B: 20>)

List/Tuple

List will be an arbitrary number of arguments (nargs="+"). Tuple will be a fixed number of arguments (nargs=NUM).

@oppapi
class Opt:
    values: List[int]
    opts: Optional[Tuple[int, str, float, bool]]
$ python nargs.py 1 2 3 --opts 10 foo 10.0 True
Opt(values=[1, 2, 3], opts=(10, 'foo', 10.0, True))

SubCommand

Union will be subcommands.

from typing import Optional, Union
from oppapi import from_args, oppapi

@oppapi
class Foo:
    a: int

@oppapi
class Bar:
    b: Optional[int]

@oppapi
class Opt:
    cmd: str
    sub: Union[Foo, Bar]

def main():
    opt = from_args(Opt)
$ python subcommand.py -h

usage: subcommand.py [-h] cmd {foo,bar} ...

positional arguments:
  cmd
  {foo,bar}

optional arguments:
  -h, --help  show this help message and exit

Flatten

TODO

LICENSE

This project is licensed under the MIT license

You might also like...
Parser for RISC OS Font control characters in Python

RISC OS Font control parsing in Python This repository contains a class (FontControlParser) for parsing font control codes from a byte squence, in Pyt

Analisador de strings feito em Python // String parser made in Python

Este é um analisador feito em Python, neste programa, estou estudando funções e a sua junção com "if's" e dados colocados pelo usuário. Neste código,

A python library for writing parser-based interactive fiction.

About IntFicPy A python library for writing parser-based interactive fiction. Currently in early development. IntFicPy Docs Parser-based interactive f

Parser for air tickets' price

Air-ticket-price-parser Parser for air tickets' price How to Install Firefox If geckodriver.exe is not compatible with your Firefox version, download

A simple string parser based on CLR to check whether a string is acceptable or not for a given grammar.

A simple string parser based on CLR to check whether a string is acceptable or not for a given grammar.

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

A parser of Windows Defender's DetectionHistory forensic artifact, containing substantial info about quarantined files and executables.

A parser of Windows Defender's DetectionHistory forensic artifact, containing substantial info about quarantined files and executables.

The parser of a timetable of tennis matches for Flashscore website

FlashscoreParser The parser of a timetable of tennis matches for Flashscore website. The program collects the schedule of tennis matches for two days

Tiling manager which runs on top of EWMH window managers.
Tiling manager which runs on top of EWMH window managers.

PyTyle is an extremely versatile and extensible tiling manager that is meant to be used on top of EWMH window managers. Its feature set was modeled af

Releases(v0.0.6)
  • v0.0.6(Oct 11, 2022)

    What's Changed

    • Fix handling optional type by @yukinarit in https://github.com/yukinarit/oppapi/pull/4

    Full Changelog: https://github.com/yukinarit/oppapi/compare/v0.0.5...v0.0.6

    Source code(tar.gz)
    Source code(zip)
  • v0.0.5(Aug 26, 2022)

    What's Changed

    • Bump to 0.0.5 by @yukinarit in https://github.com/yukinarit/oppapi/pull/3

    Full Changelog: https://github.com/yukinarit/oppapi/compare/v0.0.4...v0.0.5

    Source code(tar.gz)
    Source code(zip)
  • v0.0.4(Feb 14, 2022)

Owner
yukinarit
Python / Rust / Go
yukinarit
PatZilla is a modular patent information research platform and data integration toolkit with a modern user interface and access to multiple data sources.

PatZilla is a modular patent information research platform and data integration toolkit with a modern user interface and access to multiple data sources.

IP Tools 68 Dec 14, 2022
This tool don't used illegal ativity

ETHICALTOOL This tool for only educational purposes don't used illegal ativity @onlinehacking this tool for pkg update && pkg upgrade && pkg install g

Mrkarthick 4 Dec 23, 2021
A python program to detect rickrolls with just the youtube link.

rickroll_detector A python program to detect rickrolls with just the youtube link. Usage: clone this repo or download zip run the main.py file with py

Tricky 4 Nov 06, 2022
A basic tic tac toe game on python!

A basic tic tac toe game on python!

Shubham Kumar Chandrabansi 1 Nov 18, 2021
a wordle-solver written in python

Wordle Solver Overview This is yet another wordle solver. It is built with the word list of the official wordle website, but it should also work with

Shoubhit Dash 10 Sep 24, 2022
A basic python project which replicates the functionalities on an 8 Ball.

Magic-8-Ball To the people who wish to make decisions using a Magic 8 Ball but can't get one? I gotchu. This is a basic python project which replicate

3 Jun 24, 2021
Linux GUI app to codon optimize many single-fasta files with coding sequences , using many taxonomy ids

codon_optimize_cds_with_many_taxids_singlefasta Linux GUI app to codon optimize many single-fasta files with coding sequences, using many taxonomy ids

Olga Tsiouri 1 Jan 23, 2022
Solutions to the language assignment for Internship in JALA Technologies.

Python Assignment Solutions (JALA Technologies) Solutions to the language assignment for Internship in JALA Technologies. Features Properly formatted

Samyak Jain 2 Jan 17, 2022
This project recreates the R-based RCy3 Cytoscape Automation library as a Python package.

Python library for calling Cytoscape Automation via CyREST

Cytoscape Consortium 40 Dec 22, 2022
A Python package for searching journal publications and researchers

scholarpy A python package for searching journal publications and researchers Free software: MIT license Documentation: https://giswqs.github.io/schol

Qiusheng Wu 8 Mar 12, 2022
General tricks that may help you find bad, or noisy, labels in your dataset

doubtlab A lab for bad labels. Warning still in progress. This repository contains general tricks that may help you find bad, or noisy, labels in your

vincent d warmerdam 449 Dec 26, 2022
The fundamentals of Python!

The fundamentals of Python Author: Mohamed NIANG, Staff ML Scientist Presentation This repository contains notebooks on the fundamentals of Python. Th

Mohamed NIANG 1 Mar 15, 2022
Implementation of the Folders📂 esoteric programming language, a language with no code and just folders.

Folders.py Folders is an esoteric programming language, created by Daniel Temkin in 2015, which encodes the program entirely into the directory struct

Sina Khalili 425 Dec 17, 2022
automate some stuff so I can be more noob

dota automate some stuff so I can be more noob This is a simple project, but one that I've wanted forever! I use pyautogui, time, smtplib and datetime

Aaron Allen 17 Oct 18, 2022
Karte der Allgemeinverfügungen zu Schulschließungen oder eingeschränktem Regelbetrieb in Sachsen

SNSZ Karte Datenquelle: Allgemeinverfügungen zu Schulschließungen oder eingeschränktem Regelbetrieb in Sachsen Sächsisches Staatsministerium für Kultu

Jannis Leidel 3 Sep 26, 2022
In this project, we are going to display the battery notification and the time left for the battery to drain out using the battery capacity value.

In this project, we are going to display the battery notification and the time left for the battery to drain out using the battery capacity value.

Ritoban Biswas 1 Dec 20, 2021
NORETURN is an esoteric programming language, based around the idea of not going back

NORETURN NORETURN is an esoteric programming language, based around the idea of not going back Concept Program coded in noreturn runs over one array,

1 Dec 15, 2021
MindF**k it's a programming language as BrainFuck, but with some cool features.

MindF**k Description MindF**k it's a programming language as BrainFuck, but with some cool features. Symbol What does symbol mean Next slot Previo

tixcode 0 Jun 15, 2022
Template (v0) do Sistema Chatbot - atividade síncrona - INE5404

ine-5404-sistema-chatbot-template Template (v0) do Sistema Chatbot - atividade síncrona - INE5404 Veja abaixo um exemplo de funcionamento do sistema:

0 Dec 07, 2021
Procedurally generated Oblique Strategies for writing your own Oblique Strategies

Procedurally generated Oblique Strategies for writing your own Oblique Strategies.

Gordon Brander 13 Aug 17, 2022