Skip to main content

pyconfix

Tests Python License: MIT

A single‑file, curses‑powered, highly customizable, menuconfig‑style configuration editor for any project.


Why?

Do you need an interactive config menu like Linux menuconfig, but without C or a build step? pyconfix is forty kilobytes of pure Python you can drop into any repo—no external deps, no compilation. It also spits out JSON or Kconfig‑style header files, so it plugs straight into C/C++, CMake, Conan, Makefiles—anything that can consume a generated file.


Features

  • Hierarchical options – bool, int, string, enum, recursive groups.
  • Boolean & arithmetic dependencies with logical operators &&, ||, !, comparison/relational operators (==, !=, >, >=, <, <=), arithmetic expressions (+, -, *, /, %), and bitwise operators (&, |, ^, <<, >>).
  • Composable schemas – "include" at any level: split large configs, even factoring a single group's contents into its own file.
  • Instant search (/).
  • Abort key – Ctrl+A exits search, input boxes etc.
  • Live validation – options auto‑hide when dependencies fail.
  • Pluggable save hook – write JSON, YAML, C headers, env‑files – whatever.
  • Action options – define executable tasks with dependencies that can be run interactively or via CLI.
  • 100% standard library (Windows users: pip install windows‑curses).

Installation

pip install pyconfix

Quick start

Using the command

In order to use pyconfix in the most minimal and easy-to-use setup, just create a pyconfixfile.json file inside the current working directory, add your options to it (example bellow) and run:

pyconfix

Here's an example of how the json file could look like:

{
    "Test Config": {
        "ENABLE_FEATURE_A": true,
        "DISABLED_BY_DEFAULT": false
    }
}

The single top-level key is the configuration name, and every option is keyed by its own name. Types are deduced from the value, so a plain true/false is all you need for a boolean. See Schema format for the full set of shorthands.

Writing runner

A minimal pyconfix script that can be run and also serve as a starting point for further customizations could look like:

# menu.py
from pyconfix import pyconfix
pyconfix().load_schem().apply_config().run()

Then run it:

python menu.py

Loading the schema and applying a saved config are explicit, chainable steps (each returns the instance), and only run() starts the interactive TUI. load_schem() defaults to pyconfixfile.json. A config file passed to apply_config() must exist (a missing one raises), so to reload a previous save check that it's there first — see example.py, which loads pyconfix_output_config.json only if it exists and lets the TUI's save create it on the first run.

Press / to search, Enter to toggle/edit, s to save, q to quit. The minimal example could be found in the minimal_example.py script. To see a frther customized version you can check out example.py script which uses the schem.json file which uses more advanced features like aliases and tasks.

Custom save function

Want to emit something other than the default JSON? Pass a save_func callable to run(). It receives the flattened config dict, so you can write out any format you need:

def write_header(config_data):
    with open("config.h", "w") as f:
        for key, value in config_data.items():
            f.write(f"#define {key} {value}\n")

pyconfix().load_schem(["schem.json"]).run(save_func=write_header)

Headless / CLI mode

Drive the schema parser non‑interactively – handy for scripts and pipelines. Just skip run() (which launches the TUI) and read values after loading/applying:

python - <<'PY'
import pyconfix
cfg = pyconfix.pyconfix()
cfg.load_schem(["schem.json"])
cfg.apply_config(["prev.json"])   # apply a previously saved config (optional)
print(cfg.dump())
PY

Python API

If you’d rather drive everything from code, import the class and load/apply explicitly:

from pyconfix import pyconfix

cfg = pyconfix()
cfg.load_schem(["main.json", "extras.json"])   # parse schema files into options
cfg.apply_config(["prev.json"])                # apply a saved config (optional)
cfg.run(output_file="final.json", show_disabled=True)  # interactive TUI
print(cfg.get("HOST"))   # access a value programmatically
print(cfg.HOST)          # the same

Or done in one liner:

from pyconfix import pyconfix

pyconfix().load_schem().apply_config().run()

Method signatures for reference (load_schem and apply_config are chainable and return the instance):

pyconfix()

load_schem(schem_files: list[str] = ["pyconfixfile.json"])
# named config files must exist (missing -> ValueError); no files -> defaults kept
apply_config(config_files: list[str] | None = None, overlay: dict | None = None)

run(output_file: str = "pyconfix_output_config.json",
    show_disabled: bool = False,
    save_func: Callable[[dict], None] | None = None)

Actions

pyconfix supports defining action options that represent executable tasks. Each action can depend on other options or actions, and results are cached per execution chain.

Defining actions

Actions must be defined via Python code:

from pyconfix import pyconfix, ConfigOption

def build(x):
    print("Building...")
    return True

def deploy(x):
    print("Deploying...")
    return True

cfg = pyconfix()
cfg.load_schem(["schem.json"])
cfg.add_options(
    ConfigOption(
        name='build',
        option_type='action',
        description='Builds the software',
        dependencies=lambda x: x.ENABLE_FEATURE_A,
        default=build,
        requires=lambda x: x.LOG_LEVEL
    ),
    ConfigOption(
        name='deploy',
        option_type='action',
        description='Deploys the software',
        dependencies=lambda x: x.ENABLE_FEATURE_A,
        default=deploy,
        requires=lambda x: x.build()
    ),
)
cfg.apply_config()

Running actions

  • Interactive mode: Highlight an action in the TUI and press Enter. pyconfix will topologically sort and execute its dependencies, then the action itself, caching results.

  • CLI mode: Use the --run flag:

    python menu.py --cli --run build
    
  • Programmatically (no run() needed — just load, apply, then call):

    cfg.load_schem(["schem.json"])
    cfg.apply_config()
    result = cfg.get("build")()
    # or simply
    result = cfg.build()
    

Key bindings

Action Key
Navigate ↑ / ↓
Toggle / edit Enter
Collapse / expand c
Search /
Save s
Show description Ctrl+D
Help h
Abort search/input Ctrl+A
Quit q

Schema format

A schema is a single JSON object whose one top-level key is the configuration name. Its value maps each option name to that option's definition:

{
  "Main Config": {
    "ENABLE_FEATURE_A": true,

    "LogLevel": {
      "default": "INFO",
      "choices": ["DEBUG", "INFO", "WARN", "ERROR"],
      "dependencies": "ENABLE_FEATURE_A"
    },

    "TIMEOUT": { "default": 10, "dependencies": "ENABLE_FEATURE_A && LogLevel==DEBUG" },

    "Network": {
      "HOST": "localhost"
    },

    "include": ["extra_schem.json"]
  }
}

Because each option is keyed by its name, names are unique and must not contain whitespace. "include" is a reserved key — a list of other schema files to pull in — and it lives alongside the options.

Includes are resolved where they sit. An "include" at the top level adds the referenced files' options at the top level; an "include" placed inside a group's options adds them as members of that group. The included file's own top-level name is ignored — only its options are merged in, at the include's location. This lets you factor a group's contents out into its own file:

"Network": {
  "HOST": "localhost",
  "include": ["network_extra.json"]
}

Every option defined in network_extra.json becomes a child of Network.

Shorthands & type inference

You rarely need to spell out "type" — pyconfix deduces it from the value:

You write Becomes
"NAME": true / false bool with that default
"NAME": 42 int with that default
"NAME": "text" string with that default
"NAME": ["A", "B", "C"] enum with those choices (default = first)
{ "default": ... } type inferred from the default's JSON type
{ "choices": [...] } enum (default = default or the first choice)
{ "OTHER": ..., "MORE": ... } group — any object without type/default/choices is treated as a group whose keys are its child options

Set "type" explicitly to override inference. It is required for action options and registered aliases (e.g. tri-state), since those have no value to infer from.

Full definition object

Any option may be written in long form with these keys:

Key Short Applies to Notes
type — all bool, int, string, enum, group, action, or an alias
default def leaf options initial value (the chosen string for enum)
choices — enum list of allowed values
description desc all shown on the description page (Ctrl+D)
dependencies deps all expression controlling availability (see below)
data — all arbitrary payload passed through to your save hook
options opts group nested options (or just nest them directly)
requires — action/group predicate callable — Python API only (see note)

The Short column lists an accepted alias for the wordier fields — write "deps" instead of "dependencies", "desc", "def", or "opts". Setting both a field and its alias on the same option is an error.

Reserved keys. All of the keys above (and their short aliases, plus include) are reserved: using one as an option name raises an error, since a name and a field share the same JSON object. Matching is exact and lowercase, so an option may still be named TYPE or DATA — just not type or data.

requires is Python-only for now. It must be a callable, which JSON cannot express, so requires in a schema file raises a clear error; define it through the Python API instead. (Schema support may come in a future release.)

Supported option types

Type Notes
bool true / false
int any integer
string unicode string
enum one value from choices
group nests other options (explicit or by nesting)
action executable task option

Groups

A group can be written explicitly with "type": "group" and an "options" object, or implicitly by simply nesting named options — both forms below are equivalent:

"Network": {
  "type": "group",
  "options": {
    "HOST": "localhost"
  }
}
"Network": {
  "HOST": "localhost"
}

Use the explicit form when the group itself needs metadata such as dependencies (which cascade to every child).

Aliases

You can register alias types (currently ENUM only) and reuse them in both JSON schema files and the Python API. This is useful for reusing common choice sets like tri-state options.

  • Python usage: register the alias before loading the schema (or before run()), then create options from it:
cfg.register_alias(
    name='tri-state', 
    option_type=ConfigOptionType.ENUM,
    choices=['INTEGRATED', 'MODULE', 'DISABLED']
)

Note: Registering aliases is currently only available through the python API and only enum aliases are supported for now.

Dependency syntax – cheatsheet

!ENABLE_FEATURE_A                     # logical NOT
ENABLE_FEATURE_A && HOST==dev         # logical AND + comparison
TIMEOUT>5 || HOST==localhost          # logical OR  + relational
COUNT+5 > MAX_VALUE                   # addition + relational
SIZE-1 >= MIN_SIZE                    # subtraction + comparison
VALUE*2 == LIMIT                      # multiplication + equality
RATIO/3 < 1                           # division + relational
SIZE%4==0                             # modulus check
POWER**2 <= LIMIT                     # exponentiation + relational
BITS & 0xFF == 0xAA                   # bitwise AND + equality
FLAGS | FLAG_VERBOSE                  # bitwise OR
MASK ^ 0b1010                         # bitwise XOR
VALUE<<2 > 1024                       # left shift + relational
VALUE>>1 == 0                         # right shift + equality

Advanced usage

import pyconfix

def save_as_header(config_data):
    with open("config.h", "w") as f:
        for k, v in config_data.items():
            f.write(f"#define {k} {v}\n")

pyconfix.pyconfix().load_schem(["schem.json", "extras.json"]).run(
    output_file="settings.json",
    save_func=save_as_header,
)

Export in any format

The configurations can be exported in any desirable format by using custom save functions. Here is an example pf the current configurations bein exported in the kconfig format:

def custom_save(json_data):
    with open("output_defconfig", 'w') as f:
        for key, value in json_data.items():
            if value == None or (isinstance(value, bool) and value == False):
                continue
            if isinstance(value, str):
                f.write(f"CONFIG_{key}=\"{value}\"\n")
            else:
                f.write(f"CONFIG_{key}={value if value != True else 'y'}\n")

# ...
# The rest of the code
# ...

config = pyconfix()
config.load_schem(["schem.json"])

# ...
# The rest of the code
# ...

# hand the save hook to run(); in headless mode write it yourself with
# serializer.write_config(output_file, config.dump(), custom_save)
config.run(save_func=custom_save)

Practical remarks

There are multiple ways of attain the value of an option. Options can be treated as config's attributes or their value can be retrieved using the get function:

config = pyconfix()
config.load_schem(["schem.json"])
config.apply_config()

# Options can be treated as attributes
print(f"{config.FEATURES_NAME}")
print(f"{config.ACTIONS_NAME()}")

# Options can be retrieved using `get` function
print(f"{config.get("FEATURES_NAME", False)}")
print(f"{config.get("ACTIONS_NAME", lambda: False)()}")

IMPORTANT: The big difference between attribute syntax and get function is that in case of such an option not existing, the attribute syntax will throw an exception while the get function returns the default value provided to it.

Conan integration example

THe recommended way of retrieving the settings in conan is to use the pyconfix to read and dump the current settings. If you are using the default command and the default config names this i trivial:

# conanfile.py
from conan import ConanFile
from pyconfix import pyconfix

config = pyconfix()
config.load_schem()
config.apply_config()

class MyProject(ConanFile):
    name = "myproject"
    version = "1.0"

    # The default options can also be parsed from config.options
    # but for this example we can just type them in
    options = {
        "feature_a": [True, False],
        "log_level": ["DEBUG", "INFO", "WARN", "ERROR"],
    }
    # This could also directly be parsed from config.dump()
    default_options = {
        "feature_a": bool(config.ENABLE_FEATURE_A),
        "log_level": bool(config.LOG_LEVEL),
    }

Or if you are using a customized script version, you can create and return your config in a function and use it in your conanfile. Let's assume that function is called get_config:

# conanfile.py
from conan import ConanFile
from pyconfix import pyconfix

config = my_script.get_config()
config.apply_config()

class MyProject(ConanFile):
    name = "myproject"
    version = "1.0"

    # The default options can also be parsed from config.options
    # but for this example we can just type them in
    options = {
        "feature_a": [True, False],
        "log_level": ["DEBUG", "INFO", "WARN", "ERROR"],
    }
    # This could also directly be parsed from config.dump()
    default_options = {
        "feature_a": bool(config.ENABLE_FEATURE_A),
        "log_level": bool(config.LOG_LEVEL),
    }

This eliminates the need to sync up the customized settings inside the conanfile and running script. You could also just read the config json files directly and this might be less complex, but then the file names needs to stay sync if a custom runner script is used:

# conanfile.py
from conan import ConanFile
import os, json

_cfg = {}
try:
    with open(os.getenv("CFG", "settings.json")) as f:
        _cfg = json.load(f)
except FileNotFoundError:
    pass

class MyProject(ConanFile):
    name = "myproject"
    version = "1.0"
    options = {
        "feature_a": [True, False],
        "log_level": ["DEBUG", "INFO", "WARN", "ERROR"],
    }
    default_options = {
        "feature_a": bool(_cfg.ENABLE_FEATURE_A),
        "log_level": bool(_cfg.LOG_LEVEL),
    }

Call it with:

python pyconfix.py              # produce settings.json
CFG=settings.json conan install .

Roadmap

  • Add unit tests + GitHub Actions CI
  • Cache dependency evaluation for massive configs

Contributions are welcome – fork, hack, send PRs!


© 2025 Nemesis – MIT License

Metadata

Release files for pyconfix 1.0.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for pyconfix 1.0.1
File Size Uploaded Provenance Actions
pyconfix-1.0.1.tar.gz 49.0 kB Without provenance Details for pyconfix-1.0.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for pyconfix 1.0.1
File Interpreter ABI Platform Actions
pyconfix-1.0.1-py3-none-any.whl Python 3 none any Details for pyconfix-1.0.1-py3-none-any.whl

Total release size: 81.0 kB

Release files / pyconfix-1.0.1.tar.gz

Download URL pyconfix-1.0.1.tar.gz
Size 49.0 kB
Tags Source
SHA-256 checksum
How to use checksums
8c5d0b074a0be2ce25004177014b4b72cea780b47b4330e7f4323bf4318a715b
BLAKE2b-256 checksum
How to use checksums
dcaa6f737bc4fe3c3e0d0191d628850ab53a7733f673f247989ce21dcbc4a0f7
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.13.5

Release files / pyconfix-1.0.1-py3-none-any.whl

Download URL pyconfix-1.0.1-py3-none-any.whl
Size 32.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
64c3873fc4eb935bace01a8d5d67d13ee8f37fbb0d0c8144fb13e5fe68bb4736
BLAKE2b-256 checksum
How to use checksums
7b2584008b2c10b5a951ec2ea8cd94f02dc327b1e5cd7b7be9b49310114011da
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.13.5

Security for pyconfix 1.0.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page