Gin-Config

0.5.0 · active · verified Wed Apr 15

Gin provides a lightweight configuration framework for Python, based on dependency injection. Functions or classes can be decorated with @gin.configurable, allowing default parameter values to be supplied from a config file (or passed via the command line) using a simple but powerful syntax. This removes the need to define and maintain configuration objects or write boilerplate parameter plumbing and factory code, while often dramatically expanding a project's flexibility and configurability. It is particularly well suited for machine learning experiments. It is currently at version 0.5.0 and is actively maintained by Google.

Warnings

Install

Imports

Quickstart

To get started with Gin-Config, you define functions or classes that you want to make configurable by decorating them with `@gin.configurable`. You then create a `.gin` configuration file where you specify parameter bindings using a `function_name.parameter_name = value` syntax. Finally, you parse this configuration file in your Python application using `gin.parse_config_file()`, and Gin-Config automatically injects the configured values when the decorated functions or classes are called.

import gin

# 1. Define a configurable function or class
@gin.configurable
def greet(name='World', greeting='Hello'):
    return f"{greeting}, {name}!"

# 2. Create a config file (e.g., config.gin)
# Save this content to a file named 'config.gin':
# greet.name = 'Gin-Config User'
# greet.greeting = 'Hi there'

# 3. In your Python code, parse the config file
# For demonstration, we'll use gin.parse_config_string
# In a real application, you'd use gin.parse_config_file('config.gin')
gin_config_content = """
greet.name = 'Gin-Config User'
greet.greeting = 'Hi there'
"""
gin.parse_config_string(gin_config_content)

# 4. Call the configurable function
# Gin will automatically inject parameters from the config
result = greet()
print(result)

# You can still override configured values by passing arguments directly
result_override = greet(name='Developer')
print(result_override)

# Clear configurations (useful for testing or multiple configurations)
gin.clear_config()

# Demonstrate gin.REQUIRED
@gin.configurable
def show_required(value=gin.REQUIRED):
    return f"Required value: {value}"

# Try to call without configuring or providing 'value'
try:
    show_required()
except ValueError as e:
    print(f"Expected error for missing required parameter: {e}")

# Configure and call
gin.parse_config_string("show_required.value = 42")
print(show_required())

view raw JSON →