If launch=True and the chosen value is a callback, we call it and return None.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
form(form=None,title='')
@@ -771,9 +932,9 @@
-
Dict of {labels: default value}. The form widget infers from the default value type.
+
Dict of {labels: value}. The form widget infers from the default value type.
The dict can be nested, it can contain a subgroup.
-The default value might be mininterface.Tag that allows you to add descriptions.
+The value might be a Tag that allows you to add descriptions.
If None, the self.env is being used as a form, allowing the user to edit whole configuration.
(Previously fetched from CLI and config file.)
A checkbox example: {"my label": Tag(True, "my description")}
@@ -800,6 +961,57 @@
+
+
Returns:
+
+
+
+
Type
+
Description
+
+
+
+
+
+ FormDictOrEnv | EnvClass
+
+
+
+
dict or dataclass:
+If the form is null, the output is self.env.
+
If the form is a dict, the output is another dict.
+Whereas the original form stays intact (with the values update),
+we return a new raw dict with all values resolved
+(all Tag objects are resolved to their value).
+
original={"my label":Tag(True,"my description")}
+output=m.form(original)# Sets the label to False in the dialog
+
+# Original dict was updated
+print(original["my label"])# Tag(False, "my description")
+
+# Output dict is resolved, contains only raw values
+print(output["my label"])# False
+
+
Why this behaviour? You need to do some validation, hence you put
+Tag objects in the input dict. Then, you just need to work with the values.
+
original={"my label":Tag(True,"my description")}
+output=m.form(original)# Sets the label to False in the dialog
+output["my_label"]
+
+
In the case you are willing to re-use the dict, you need not to lose the definitions,
+hence you end up with accessing via the .val.
Use a common dataclass, a Pydantic BaseModel or an attrs model to store the configuration. Wrap it to the run method that returns an interface m. Access the configuration via m.env or use it to prompt the user m.is_yes("Is that alright?"). To do any advanced things, stick the value to a powerful Tag. For a validation only, use its Validation alias.
+
Use a common dataclass, a Pydantic BaseModel or an attrs model to store the configuration. Wrap it to the run method that returns an interface m. Access the configuration via m.env or use it to prompt the user m.is_yes("Is that alright?").
+
To do any advanced things, stick the value to a powerful Tag. For a validation only, use its Validation alias.
Supported types
-
Various types are supported: scalars, functions, well-known objects (Path), iterables, custom classes.
+
Various types are supported:
+
+
scalars
+
functions
+
well-known objects (Path, datetime)
+
iterables (like list[Path])
+
custom classes (somewhat)
+
union types (like int | None)
+
Take a look how it works with the variables organized in a dataclass:
""" A dummy number """my_boolean:bool=True""" A dummy boolean """
-my_path:Path=Path("/tmp")
-""" A dummy path """
-
-
-m=run(Env)# m.env contains an Env instance
-m.form()# Prompt a dialog; m.form() without parameter edits m.env
-print(m.env)
-# Env(my_number=1, my_boolean=True, my_path=PosixPath('/tmp'),
-# my_point=<__main__.Point object at 0x7ecb5427fdd0>)
+my_conditional_number:int|None=None
+""" A number that can be null if left empty """
+my_path:Path=Path("/tmp")
+""" A dummy path """
+
+
+m=run(Env)# m.env contains an Env instance
+m.form()# Prompt a dialog; m.form() without parameter edits m.env
+print(m.env)
+# Env(my_number=1, my_boolean=True, my_path=PosixPath('/tmp'),
+# my_point=<__main__.Point object at 0x7ecb5427fdd0>)
Variables organized in a dict:
@@ -550,12 +599,29 @@
Nested configuration
...print(config.further.host)# example.org
-
A subset might be defaulted in YAML:
-
further:
-host:example.com
+
The attributes can by defaulted by CLI:
+
$./program.py --further.host example.net
+
+
And in a YAML config file. Note that you are not obliged to define all the attributes, a subset will do.
+(Ex. you do not need to specify token too.)
+
further:
+host:example.com
-
Or by CLI:
-
$./program.py --further.host example.net
+
All possible interfaces
+
Normally, you get an interface through mininterface.run
+but if you do not wish to parse CLI and config file, you can invoke one directly.
+
Several interfaces exist:
+
+
Mininterface – The base interface the others are fully compatible with.
+
GuiInterface – A tkinter window.
+
TuiInterface – An interactive terminal.
+
TextualInterface – If textual installed, rich interface is used.
+
TextInterface – Plain text only interface with no dependency as a fallback.
+
ReplInterface – A debug terminal. Invokes a breakpoint after every dialog.
fromdataclassesimportdataclass
+fromtypingimportAnnotated
+frommininterfaceimportrun,Choices
+
+@dataclass
+classEnv:
+foo:Annotated["str",Choices("one","two")]="one"
+
+# `Choices` is an alias for `Tag(choices=)`
+
+m=run(Env)
+m.form()# prompts a dialog
+
@@ -865,7 +895,7 @@
-
Read only. The original value, preceding UI change. Handy while validating.
+
Meant to be read only in callbacks. The original value, preceding UI change. Handy while validating.
defcheck(tag.val):iftag.val!=tag.original_val:return"You have to change the value."
@@ -875,23 +905,6 @@
-
-
-
-
-
- error_text=None
-
-
-
-
-
-
-
Read only. Error text if type check or validation fail and the UI has to be revised
It was all the code you need. No lengthy blocks of code imposed by an external dependency. Besides the GUI/TUI, you receive powerful YAML-configurable CLI parsing.
Wrapper between the tyroargparse replacement and tkinter_form that converts dicts into a GUI.
Writing a small and useful program might be a task that takes fifteen minutes. Adding a CLI to specify the parameters is not so much overhead. But building a simple GUI around it? HOURS! Hours spent on researching GUI libraries, wondering why the Python desktop app ecosystem lags so far behind the web world. All you need is a few input fields validated through a clickable window... You do not deserve to add hundred of lines of the code just to define some editable fields. Mininterface is here to help.
classEnv:nested_config:NestedEnv
-my_number:int=5
-""" This is just a dummy number """
+mandatory_str:str
+""" As there is not default value, you will be prompted automatically to fill up the field """
-my_string:str="Hello"
-""" A dummy string """
+my_number:int|None=None
+""" This is not just a dummy number, if left empty, it is None. """
-my_flag:bool=False
-""" Checkbox test """
+my_string:str="Hello"
+""" A dummy string """
-my_validated:Annotated[str,Validation(not_empty)]="hello"
-""" A validated field """
+my_flag:bool=False
+""" Checkbox test """
-m=run(Env,title="My program")
-# See some values
-print(m.env.nested_config.another_number)# 7
-print(m.env)
-# Env(nested_config=NestedEnv(another_number=7), my_number=5, my_string='Hello', my_flag=False, my_validated='hello')
-
-# Edit values in a dialog
-m.form()
+my_validated:Annotated[str,Validation(not_empty)]="hello"
+""" A validated field """
+
+m=run(Env,title="My program")
+# See some values
+print(m.env.nested_config.another_number)# 7
+print(m.env)
+# Env(nested_config=NestedEnv(another_number=7), my_number=5, my_string='Hello', my_flag=False, my_validated='hello')
+
+# Edit values in a dialog
+m.form()
+
+
Form with paths
+
We have a dict with some paths. Here is how it looks.
+
frompathlibimportPath
+frommininterfaceimportrun,Tag
+
+m=run(title="My program")
+my_dictionary={
+"paths":Tag("",annotation=list[Path]),
+"default_paths":Tag([Path("/tmp"),Path("/usr")],annotation=list[Path])
+}
+
+# Edit values in a dialog
+m.form(my_dictionary)
diff --git a/search/search_index.json b/search/search_index.json
index b8ad295..aeca817 100644
--- a/search/search_index.json
+++ b/search/search_index.json
@@ -1 +1 @@
-{"config":{"lang":["en"],"separator":"[\\s\\-]+","pipeline":["stopWordFilter"]},"docs":[{"location":"","title":"Mininterface \u2013 access to GUI, TUI, CLI and config files","text":"
Write the program core, do not bother with the input/output.
Check out the code, which is surprisingly short, that displays such a window or its textual fallback.
from dataclasses import dataclass\nfrom mininterface import run\n\n@dataclass\nclass Env:\n \"\"\"Set of options.\"\"\"\n\n test: bool = False\n \"\"\" My testing flag \"\"\"\n\n important_number: int = 4\n \"\"\" This number is very important \"\"\"\n\nif __name__ == \"__main__\":\n env = run(Env, prog=\"My application\").env\n # Attributes are suggested by the IDE\n # along with the hint text 'This number is very important'.\n print(env.important_number)\n
It was all the code you need. No lengthy blocks of code imposed by an external dependency. Besides the GUI/TUI, you receive powerful YAML-configurable CLI parsing.
$ ./hello.py\nusage: My application [-h] [--test | --no-test] [--important-number INT]\n\nSet of options.\n\n\u256d\u2500 options \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256e\n\u2502 -h, --help show this help message and exit \u2502\n\u2502 --test, --no-test My testing flag (default: False) \u2502\n\u2502 --important-number INT This number is very important (default: 4) \u2502\n\u2570\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256f\n
Loading config file is a piece of cake. Alongside program.py, put program.yaml and put there some of the arguments. They are seamlessly taken as defaults.
Check out several useful methods to handle user dialogues. Here we bound the interface to a with statement that redirects stdout directly to the window.
with run(Env) as m:\n print(f\"Your important number is {m.env.important_number}\")\n boolean = m.is_yes(\"Is that alright?\")\n
Wrapper between the tyro argparse replacement and tkinter_form that converts dicts into a GUI.
Writing a small and useful program might be a task that takes fifteen minutes. Adding a CLI to specify the parameters is not so much overhead. But building a simple GUI around it? HOURS! Hours spent on researching GUI libraries, wondering why the Python desktop app ecosystem lags so far behind the web world. All you need is a few input fields validated through a clickable window... You do not deserve to add hundred of lines of the code just to define some editable fields. Mininterface is here to help.
The config variables needed by your program are kept in cozy dataclasses. Write less! The syntax of tyro does not require any overhead (as its argparse alternatives do). You just annotate a class attribute, append a simple docstring and get a fully functional application: * Call it as program.py --help to display full help. * Use any flag in CLI: program.py --test causes env.test be set to True. * The main benefit: Launch it without parameters as program.py to get a full working window with all the flags ready to be edited. * Running on a remote machine? Automatic regression to the text interface.
from typing import Annotated\nfrom dataclasses import dataclass\nfrom mininterface.validators import not_empty\nfrom mininterface import run, Tag, Validation\n\n@dataclass\nclass NestedEnv:\n another_number: int = 7\n \"\"\" This field is nested \"\"\"\n\n@dataclass\nclass Env:\n nested_config: NestedEnv\n\n my_number: int = 5\n \"\"\" This is just a dummy number \"\"\"\n\n my_string: str = \"Hello\"\n \"\"\" A dummy string \"\"\"\n\n my_flag: bool = False\n \"\"\" Checkbox test \"\"\"\n\n my_validated: Annotated[str, Validation(not_empty)] = \"hello\"\n \"\"\" A validated field \"\"\"\n\nm = run(Env, title=\"My program\")\n# See some values\nprint(m.env.nested_config.another_number) # 7\nprint(m.env)\n# Env(nested_config=NestedEnv(another_number=7), my_number=5, my_string='Hello', my_flag=False, my_validated='hello')\n\n# Edit values in a dialog\nm.form()\n
The base interface. You get one through mininterface.run which fills CLI arguments and config file to mininterface.env or you can create one directly (without benefiting from the CLI parsing).
"},{"location":"Mininterface/#mininterface.mininterface.Mininterface.env","title":"env: EnvClass = _env or SimpleNamespace()instance-attribute","text":"
Parsed arguments, fetched from cli Contains whole configuration (previously fetched from CLI and config file).
$ program.py --number 10\n
from dataclasses import dataclass\nfrom mininterface import run\n\n@dataclass\nclass Env:\n number: int = 3\n text: str = \"\"\n\nm = run(Env)\nprint(m.env.number) # 10\n
Name Type Description Default formFormDictOrEnv | None
Dict of {labels: default value}. The form widget infers from the default value type. The dict can be nested, it can contain a subgroup. The default value might be mininterface.Tag that allows you to add descriptions. If None, the self.env is being used as a form, allowing the user to edit whole configuration. (Previously fetched from CLI and config file.) A checkbox example: {\"my label\": Tag(True, \"my description\")}
Use a common dataclass, a Pydantic BaseModel or an attrs model to store the configuration. Wrap it to the run method that returns an interface m. Access the configuration via m.env or use it to prompt the user m.is_yes(\"Is that alright?\"). To do any advanced things, stick the value to a powerful Tag. For a validation only, use its Validation alias.
When invoked directly, it creates simple GUI dialogs.
$ mininterface --help\nusage: Mininterface [-h] [OPTIONS]\n\nSimple GUI dialog. Outputs the value the user entered.\n\n\u256d\u2500 options \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256e\n\u2502 -h, --help show this help message and exit \u2502\n\u2502 --alert STR Display the OK dialog with text. (default: '') \u2502\n\u2502 --ask STR Prompt the user to input a text. (default: '') \u2502\n\u2502 --ask-number STR Prompt the user to input a number. Empty input = 0. (default: '') \u2502\n\u2502 --is-yes STR Display confirm box, focusing yes. (default: '') \u2502\n\u2502 --is-no STR Display confirm box, focusing no. (default: '') \u2502\n\u2570\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256f\n
You can fetch a value to i.e. a bash script.
$ mininterface --ask-number \"What's your age?\" # GUI window invoked\n18\n
"},{"location":"Tag/","title":"Tag","text":"
Wrapper around a value that encapsulates a description, validation etc. When you provide a value to an interface, you may instead use this object.
Bridge between the input values and a UI widget. The widget is created with the help of this object, then transforms the value back (str to int conversion etc).
When the user submits the form, the values are validated (and possibly transformed) with a callback function. If the validation fails, user is prompted to edit the value. Return True if validation succeeded or False or an error message when it failed.
ValidationResult is a bool or the error message (that implicitly means it has failed).
def check(tag: Tag):\n if tag.val < 10:\n return \"The value must be at least 10\"\nm.form({\"number\", Tag(12, validation=check)})\n
Either use a custom callback function or mininterface.validators.
from mininterface.validators import not_empty\nm.form({\"number\", Tag(\"\", validation=not_empty)})\n# User cannot leave the field empty.\n
You may use the validation in a type annotation.
from mininterface import Tag, Validation\n@dataclass\nclass Env:\n my_text: Annotated[str, Validation(not_empty) = \"will not be emtpy\"\n\n # which is an alias for:\n # my_text: Annotated[str, Tag(validation=not_empty)] = \"will not be emtpy\"\n
NOTE Undocumented feature, we can return tuple [ValidationResult, FieldValue] to set the self.val.
from mininterface import Tag, Validation\n@dataclass\nclass Env:\n my_text: Annotated[str, Validation(not_empty) = \"will not be emtpy\"\n\n # which is an alias for:\n # my_text: Annotated[str, Tag(validation=not_empty)] = \"will not be emtpy\"\n
Parameters:
Name Type Description Default checkCallable[[Tag], ValidationResult | tuple[ValidationResult, TagValue]]
Functions suitable for Tag validation. When the user submits a value whose validation fails, they are prompted to edit the value.
m = run()\nmy_dict = m.form({\"my_text\", Tag(\"\", validation=validators.not_empty)})\nmy_dict[\"my_text\"] # You can be sure the value is not empty here.\n
Note that alternatively to this module, you may validate with Pydantic or an attrs model.
Assures that Tag the user has written a value and did not let the field empty.
from mininterface import Tag, validators, run\n\nm = run()\nm.form({\"my_text\": Tag(\"\", validation=validators.not_empty)})\n# User cannot leave the string field empty.\n
When submitting an empty value, a warning appears:
Note that for Path, an empty string is converted to an empty Path('.'), hence '.' too is considered as an empty input and the user is not able to set '.' as a value. This does not seem to me as a bad behaviour as in CLI you clearly see the CWD, whereas in a UI the CWD is not evident.
Parameters:
Name Type Description Default tagTag required"},{"location":"Validation/#mininterface.validators.limit","title":"limit(maxOrMin=None, max_=None, lt=None, gt=None, transform=False)","text":"
Limit a number range or a string length.
Either use as limit(maximum) or limit(minimum, maximum).
Parameters:
Name Type Description Default maximumint
limit(maximum) \u2013 from zero (including) to maximum (including)
required minimumint
limit(minimum, maximum) \u2013 From minimum (including) to maximum (including)
required ltfloat | None
lesser than
Nonegtfloat | None
greater than
Nonetransformbool
If the value is not withing the limit, transform it to a boundary.
from mininterface import run, Tag\nfrom mininterface.validators import limit\n\nm = run()\nm.form({\"my_number\": Tag(2, validation=limit(1, 10, transform=True))})\n# Put there '50' \u2192 transformed to 10 and dialog reappears\n# with 'Value must be between 1 and 10.'\n
False"},{"location":"run/","title":"Run","text":"
The main access, start here. Wrap your configuration dataclass into run to access the interface. An interface is chosen automatically, with the preference of the graphical one, regressed to a text interface for machines without display. Besides, if given a configuration dataclass, the function enriches it with the CLI commands and possibly with the default from a config file if such exists. It searches the config file in the current working directory, with the program name ending on .yaml, ex: program.py will fetch ./program.yaml.
Parameters:
Name Type Description Default env_classType[EnvClass] | None
Dataclass with the configuration. Their values will be modified with the CLI arguments.
Noneask_on_empty_clibool
If program was launched with no arguments (empty CLI), invokes self.form() to edit the fields. (Withdrawn when ask_for_missing happens.)
$ program.py # omitting all parameters\n# Dialog for `number` and `text` appears\n$ program.py --number 3\n# No dialog appears\n
Falsetitlestr
The main title. If not set, taken from prog or program name.
''config_filePath | str | bool
File to load YAML to be merged with the configuration. You do not have to re-define all the settings in the config file, you can choose a few. If set to True (default), we try to find one in the current working dir, whose name stem is the same as the program's. Ex: program.py will search for program.yaml. If False, no config file is used.
Trueadd_verbositybool
Adds the verbose flag that automatically sets the level to logging.INFO (-v) or logging.DEBUG (-vv).
import logging\nlogger = logging.getLogger(__name__)\n\nm = run(Env, add_verbosity=True)\nlogger.info(\"Info shown\") # needs `-v` or `--verbose`\nlogger.debug(\"Debug not shown\") # needs `-vv`\n# $ program.py --verbose\n# Info shown\n
$ program.py --verbose\nInfo shown\n
Trueask_for_missingbool
If some required fields are missing at startup, we ask for them in a UI instead of program exit.
$ program.py # omitting --required-number\n# Dialog for `required_number` appears\n
TrueinterfaceType[Mininterface]
Which interface to prefer. By default, we use the GUI, the fallback is the TUI. See the full list of possible interfaces.
GuiInterface or TuiInterface Kwargs
The same as for argparse.ArgumentParser.
Returns:
Type Description Mininterface[EnvClass]
An interface, ready to be used.
You cay context manager the function by a with statement. The stdout will be redirected to the interface (ex. a GUI window). TODO add wrap example
Undocumented experimental: The env_class may be a function as well. We invoke its parameters. However, as Mininterface.env stores the output of the function instead of the Argparse namespace, methods like Mininterface.form(None) (to ask for editing the env values) will work unpredictibly. Also, the config file seems to be fetched only for positional (missing) parameters, and ignored for keyword (filled) parameters. It seems to be this is the tyro's deal and hence it might start working any time. If not, we might help it this way: if isinstance(config, FunctionType): config = lambda: config(**kwargs[\"default\"])
Undocumented experimental: default keyword argument for tyro may serve for default values instead of a config file.
"}]}
\ No newline at end of file
+{"config":{"lang":["en"],"separator":"[\\s\\-]+","pipeline":["stopWordFilter"]},"docs":[{"location":"","title":"Mininterface \u2013 access to GUI, TUI, CLI and config files","text":"
Write the program core, do not bother with the input/output.
Check out the code, which is surprisingly short, that displays such a window or its textual fallback.
from dataclasses import dataclass\nfrom mininterface import run\n\n@dataclass\nclass Env:\n \"\"\"Set of options.\"\"\"\n\n test: bool = False\n \"\"\" My testing flag \"\"\"\n\n important_number: int = 4\n \"\"\" This number is very important \"\"\"\n\nif __name__ == \"__main__\":\n env = run(Env, prog=\"My application\").env\n # Attributes are suggested by the IDE\n # along with the hint text 'This number is very important'.\n print(env.important_number)\n
It was all the code you need. No lengthy blocks of code imposed by an external dependency. Besides the GUI/TUI, you receive powerful YAML-configurable CLI parsing.
$ ./hello.py\nusage: My application [-h] [--test | --no-test] [--important-number INT]\n\nSet of options.\n\n\u256d\u2500 options \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256e\n\u2502 -h, --help show this help message and exit \u2502\n\u2502 --test, --no-test My testing flag (default: False) \u2502\n\u2502 --important-number INT This number is very important (default: 4) \u2502\n\u2570\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256f\n
Loading config file is a piece of cake. Alongside program.py, put program.yaml and put there some of the arguments. They are seamlessly taken as defaults.
Check out several useful methods to handle user dialogues. Here we bound the interface to a with statement that redirects stdout directly to the window.
with run(Env) as m:\n print(f\"Your important number is {m.env.important_number}\")\n boolean = m.is_yes(\"Is that alright?\")\n
Wrapper between the tyro argparse replacement and tkinter_form that converts dicts into a GUI.
Writing a small and useful program might be a task that takes fifteen minutes. Adding a CLI to specify the parameters is not so much overhead. But building a simple GUI around it? HOURS! Hours spent on researching GUI libraries, wondering why the Python desktop app ecosystem lags so far behind the web world. All you need is a few input fields validated through a clickable window... You do not deserve to add hundred of lines of the code just to define some editable fields. Mininterface is here to help.
The config variables needed by your program are kept in cozy dataclasses. Write less! The syntax of tyro does not require any overhead (as its argparse alternatives do). You just annotate a class attribute, append a simple docstring and get a fully functional application: * Call it as program.py --help to display full help. * Use any flag in CLI: program.py --test causes env.test be set to True. * The main benefit: Launch it without parameters as program.py to get a full working window with all the flags ready to be edited. * Running on a remote machine? Automatic regression to the text interface.
from typing import Annotated\nfrom dataclasses import dataclass\nfrom mininterface.validators import not_empty\nfrom mininterface import run, Tag, Validation\n\n@dataclass\nclass NestedEnv:\n another_number: int = 7\n \"\"\" This field is nested \"\"\"\n\n@dataclass\nclass Env:\n nested_config: NestedEnv\n\n mandatory_str: str\n \"\"\" As there is not default value, you will be prompted automatically to fill up the field \"\"\"\n\n my_number: int | None = None\n \"\"\" This is not just a dummy number, if left empty, it is None. \"\"\"\n\n my_string: str = \"Hello\"\n \"\"\" A dummy string \"\"\"\n\n my_flag: bool = False\n \"\"\" Checkbox test \"\"\"\n\n my_validated: Annotated[str, Validation(not_empty)] = \"hello\"\n \"\"\" A validated field \"\"\"\n\nm = run(Env, title=\"My program\")\n# See some values\nprint(m.env.nested_config.another_number) # 7\nprint(m.env)\n# Env(nested_config=NestedEnv(another_number=7), my_number=5, my_string='Hello', my_flag=False, my_validated='hello')\n\n# Edit values in a dialog\nm.form()\n
"},{"location":"#form-with-paths","title":"Form with paths","text":"
We have a dict with some paths. Here is how it looks.
from pathlib import Path\nfrom mininterface import run, Tag\n\nm = run(title=\"My program\")\nmy_dictionary = {\n \"paths\": Tag(\"\", annotation=list[Path]),\n \"default_paths\": Tag([Path(\"/tmp\"), Path(\"/usr\")], annotation=list[Path])\n }\n\n# Edit values in a dialog\nm.form(my_dictionary)\n
The base interface. You get one through mininterface.run which fills CLI arguments and config file to mininterface.env or you can create one directly (without benefiting from the CLI parsing).
Name Type Description Default formFormDictOrEnv | None
Dict of {labels: value}. The form widget infers from the default value type. The dict can be nested, it can contain a subgroup. The value might be a Tag that allows you to add descriptions. If None, the self.env is being used as a form, allowing the user to edit whole configuration. (Previously fetched from CLI and config file.) A checkbox example: {\"my label\": Tag(True, \"my description\")}
Nonetitlestr
Optional form title
''
Returns:
Type Description FormDictOrEnv | EnvClass
dict or dataclass: If the form is null, the output is self.env.
If the form is a dict, the output is another dict. Whereas the original form stays intact (with the values update), we return a new raw dict with all values resolved (all Tag objects are resolved to their value).
original = {\"my label\": Tag(True, \"my description\")}\noutput = m.form(original) # Sets the label to False in the dialog\n\n# Original dict was updated\nprint(original[\"my label\"]) # Tag(False, \"my description\")\n\n# Output dict is resolved, contains only raw values\nprint(output[\"my label\"]) # False\n
Why this behaviour? You need to do some validation, hence you put Tag objects in the input dict. Then, you just need to work with the values.
original = {\"my label\": Tag(True, \"my description\")}\noutput = m.form(original) # Sets the label to False in the dialog\noutput[\"my_label\"]\n
In the case you are willing to re-use the dict, you need not to lose the definitions, hence you end up with accessing via the .val.
original = {\"my label\": Tag(True, \"my description\")}\n\nfor i in range(10):\n m.form(original, f\"Attempt {i}\")\n print(\"The result\", original[\"my label\"].val)\n
Use a common dataclass, a Pydantic BaseModel or an attrs model to store the configuration. Wrap it to the run method that returns an interface m. Access the configuration via m.env or use it to prompt the user m.is_yes(\"Is that alright?\").
To do any advanced things, stick the value to a powerful Tag. For a validation only, use its Validation alias.
Take a look how it works with the variables organized in a dataclass:
from dataclasses import dataclass\nfrom pathlib import Path\n\nfrom mininterface import run\n\n\n@dataclass\nclass Env:\n my_number: int = 1\n \"\"\" A dummy number \"\"\"\n my_boolean: bool = True\n \"\"\" A dummy boolean \"\"\"\n my_conditional_number: int | None = None\n \"\"\" A number that can be null if left empty \"\"\"\n my_path: Path = Path(\"/tmp\")\n \"\"\" A dummy path \"\"\"\n\n\nm = run(Env) # m.env contains an Env instance\nm.form() # Prompt a dialog; m.form() without parameter edits m.env\nprint(m.env)\n# Env(my_number=1, my_boolean=True, my_path=PosixPath('/tmp'),\n# my_point=<__main__.Point object at 0x7ecb5427fdd0>)\n
Variables organized in a dict:
Along scalar types, there is (basic) support for common iterables or custom classes.
When invoked directly, it creates simple GUI dialogs.
$ mininterface --help\nusage: Mininterface [-h] [OPTIONS]\n\nSimple GUI dialog. Outputs the value the user entered.\n\n\u256d\u2500 options \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256e\n\u2502 -h, --help show this help message and exit \u2502\n\u2502 --alert STR Display the OK dialog with text. (default: '') \u2502\n\u2502 --ask STR Prompt the user to input a text. (default: '') \u2502\n\u2502 --ask-number STR Prompt the user to input a number. Empty input = 0. (default: '') \u2502\n\u2502 --is-yes STR Display confirm box, focusing yes. (default: '') \u2502\n\u2502 --is-no STR Display confirm box, focusing no. (default: '') \u2502\n\u2570\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256f\n
You can fetch a value to i.e. a bash script.
$ mininterface --ask-number \"What's your age?\" # GUI or TUI window invoked\n18\n
"},{"location":"Tag/","title":"Tag","text":"
Wrapper around a value that encapsulates a description, validation etc. When you provide a value to an interface, you may instead use this object.
Bridge between the input values and a UI widget. The widget is created with the help of this object, then transforms the value back (str to int conversion etc).
When the user submits the form, the values are validated (and possibly transformed) with a callback function. If the validation fails, user is prompted to edit the value. Return True if validation succeeded or False or an error message when it failed.
ValidationResult is a bool or the error message (that implicitly means it has failed).
def check(tag: Tag):\n if tag.val < 10:\n return \"The value must be at least 10\"\nm.form({\"number\", Tag(12, validation=check)})\n
Either use a custom callback function or mininterface.validators.
from mininterface.validators import not_empty\nm.form({\"number\", Tag(\"\", validation=not_empty)})\n# User cannot leave the field empty.\n
You may use the validation in a type annotation.
from mininterface import Tag, Validation\n@dataclass\nclass Env:\n my_text: Annotated[str, Validation(not_empty) = \"will not be emtpy\"\n\n # which is an alias for:\n # my_text: Annotated[str, Tag(validation=not_empty)] = \"will not be emtpy\"\n
NOTE Undocumented feature, we can return tuple [ValidationResult, FieldValue] to set the self.val.
from mininterface import Tag, Validation\n@dataclass\nclass Env:\n my_text: Annotated[str, Validation(not_empty) = \"will not be emtpy\"\n\n # which is an alias for:\n # my_text: Annotated[str, Tag(validation=not_empty)] = \"will not be emtpy\"\n
Parameters:
Name Type Description Default checkCallable[[Tag], ValidationResult | tuple[ValidationResult, TagValue]]
Functions suitable for Tag validation. When the user submits a value whose validation fails, they are prompted to edit the value.
m = run()\nmy_dict = m.form({\"my_text\", Tag(\"\", validation=validators.not_empty)})\nmy_dict[\"my_text\"] # You can be sure the value is not empty here.\n
Note that alternatively to this module, you may validate with Pydantic or an attrs model.
Assures that Tag the user has written a value and did not let the field empty.
from mininterface import Tag, validators, run\n\nm = run()\nm.form({\"my_text\": Tag(\"\", validation=validators.not_empty)})\n# User cannot leave the string field empty.\n
When submitting an empty value, a warning appears:
Note that for Path, an empty string is converted to an empty Path('.'), hence '.' too is considered as an empty input and the user is not able to set '.' as a value. This does not seem to me as a bad behaviour as in CLI you clearly see the CWD, whereas in a UI the CWD is not evident.
Parameters:
Name Type Description Default tagTag required"},{"location":"Validation/#mininterface.validators.limit","title":"limit(maxOrMin=None, max_=None, lt=None, gt=None, transform=False)","text":"
Limit a number range or a string length.
Either use as limit(maximum) or limit(minimum, maximum).
Parameters:
Name Type Description Default maximumint
limit(maximum) \u2013 from zero (including) to maximum (including)
required minimumint
limit(minimum, maximum) \u2013 From minimum (including) to maximum (including)
required ltfloat | None
lesser than
Nonegtfloat | None
greater than
Nonetransformbool
If the value is not withing the limit, transform it to a boundary.
from mininterface import run, Tag\nfrom mininterface.validators import limit\n\nm = run()\nm.form({\"my_number\": Tag(2, validation=limit(1, 10, transform=True))})\n# Put there '50' \u2192 transformed to 10 and dialog reappears\n# with 'Value must be between 1 and 10.'\n
False"},{"location":"run/","title":"Run","text":"
The main access, start here. Wrap your configuration dataclass into run to access the interface. An interface is chosen automatically, with the preference of the graphical one, regressed to a text interface for machines without display. Besides, if given a configuration dataclass, the function enriches it with the CLI commands and possibly with the default from a config file if such exists. It searches the config file in the current working directory, with the program name ending on .yaml, ex: program.py will fetch ./program.yaml.
Parameters:
Name Type Description Default env_classType[EnvClass] | None
Dataclass with the configuration. Their values will be modified with the CLI arguments.
Noneask_on_empty_clibool
If program was launched with no arguments (empty CLI), invokes self.form() to edit the fields. (Withdrawn when ask_for_missing happens.)
$ program.py # omitting all parameters\n# Dialog for `number` and `text` appears\n$ program.py --number 3\n# No dialog appears\n
Falsetitlestr
The main title. If not set, taken from prog or program name.
''config_filePath | str | bool
File to load YAML to be merged with the configuration. You do not have to re-define all the settings in the config file, you can choose a few. If set to True (default), we try to find one in the current working dir, whose name stem is the same as the program's. Ex: program.py will search for program.yaml. If False, no config file is used.
Trueadd_verbositybool
Adds the verbose flag that automatically sets the level to logging.INFO (-v) or logging.DEBUG (-vv).
import logging\nlogger = logging.getLogger(__name__)\n\nm = run(Env, add_verbosity=True)\nlogger.info(\"Info shown\") # needs `-v` or `--verbose`\nlogger.debug(\"Debug not shown\") # needs `-vv`\n# $ program.py --verbose\n# Info shown\n
$ program.py --verbose\nInfo shown\n
Trueask_for_missingbool
If some required fields are missing at startup, we ask for them in a UI instead of program exit.
$ program.py # omitting --required-number\n# Dialog for `required_number` appears\n
TrueinterfaceType[Mininterface]
Which interface to prefer. By default, we use the GUI, the fallback is the TUI. See the full list of possible interfaces.
GuiInterface or TuiInterface Kwargs
The same as for argparse.ArgumentParser.
Returns:
Type Description Mininterface[EnvClass]
An interface, ready to be used.
You cay context manager the function by a with statement. The stdout will be redirected to the interface (ex. a GUI window). TODO add wrap example
Undocumented experimental: The env_class may be a function as well. We invoke its parameters. However, as Mininterface.env stores the output of the function instead of the Argparse namespace, methods like Mininterface.form(None) (to ask for editing the env values) will work unpredictibly. Also, the config file seems to be fetched only for positional (missing) parameters, and ignored for keyword (filled) parameters. It seems to be this is the tyro's deal and hence it might start working any time. If not, we might help it this way: if isinstance(config, FunctionType): config = lambda: config(**kwargs[\"default\"])
Undocumented experimental: default keyword argument for tyro may serve for default values instead of a config file.
"}]}
\ No newline at end of file
diff --git a/sitemap.xml.gz b/sitemap.xml.gz
index 0eeedbe..7445a14 100644
Binary files a/sitemap.xml.gz and b/sitemap.xml.gz differ