SCons.Variables package#

Module contents#

Adds user-friendly customizable variables to an SCons build.

class SCons.Variables.Variable[source]#

Bases: object

A Build Variable.

__lt__(other)[source]#

Comparison fuction so Variable instances sort.

__str__() str[source]#

Provide a way to “print” a Variable object.

aliases#
converter#
default#
do_subst#
help#
key#
validator#
class SCons.Variables.Variables(files: str | Sequence[str] | None = None, args: dict | None = None, is_global: bool = False)[source]#

Bases: object

A container for multiple Build Variables.

Includes methods to updates the environment with the variables, and to render the help text.

Parameters:
  • files – string or list of strings naming variable config scripts (default None)

  • args – dictionary to override values set from files. (default None)

  • is_global – if true, return a global singleton Variables object instead of a fresh instance. Currently inoperable (default False)

Changed in version 4.8.0: The default for is_global changed to False (previously True but it had no effect due to an implementation error).

Deprecated since version 4.8.0: is_global is deprecated.

Add(key: str | Sequence, *args, **kwargs) None[source]#

Add a Build Variable.

Parameters:
  • key – the name of the variable, or a 5-tuple (or other sequence). If key is a tuple, and there are no additional arguments except the help, default, validator and converter keyword arguments, key is unpacked into the variable name plus the help, default, validator and converter arguments; if there are additional arguments, the first elements of key is taken as the variable name, and the remainder as aliases.

  • args – optional positional arguments, corresponding to the help, default, validator and converter keyword args.

  • kwargs – arbitrary keyword arguments used by the variable itself.

Keyword Arguments:
  • help – help text for the variable (default: empty string)

  • default – default value for variable (default: None)

  • validator – function called to validate the value (default: None)

  • converter – function to be called to convert the variable’s value before putting it in the environment. (default: None)

  • subst – perform substitution on the value before the converter and validator functions (if any) are called (default: True)

New in version 4.8.0: The subst keyword argument is now specially recognized.

AddVariables(*optlist) None[source]#

Add a list of Build Variables.

Each list element is a tuple/list of arguments to be passed on to the underlying method for adding variables.

Example:

opt = Variables()
opt.AddVariables(
    ('debug', '', 0),
    ('CC', 'The C compiler'),
    ('VALIDATE', 'An option for testing validation', 'notset', validator, None),
)
FormatVariableHelpText(env, key: str, help: str, default, actual, aliases: List[str] | None = None) str[source]#

Format the help text for a single variable.

The caller is responsible for obtaining all the values, although now the Variable class is more publicly exposed, this method could easily do most of that work - however that would change the existing published API.

GenerateHelpText(env, sort: bool | Callable = False) str[source]#

Generate the help text for the Variables object.

Parameters:
  • env – an environment that is used to get the current values of the variables.

  • sort – Either a comparison function used for sorting (must take two arguments and return -1, 0 or 1) or a boolean to indicate if it should be sorted.

Save(filename, env) None[source]#

Save the variables to a script.

Saves all the variables which have non-default settings to the given file as Python expressions. This script can then be used to load the variables for a subsequent run. This can be used to create a build variable “cache” or capture different configurations for selection.

Parameters:
  • filename – Name of the file to save into

  • env – the environment to get the option values from

UnknownVariables() dict[source]#

Return dict of unknown variables.

Identifies variables that were not recognized in this object.

Update(env, args: dict | None = None) None[source]#

Update an environment with the Build Variables.

Parameters:
  • env – the environment to update.

  • args – a dictionary of keys and values to update in env. If omitted, uses the saved args

__str__() str[source]#

Provide a way to “print” a Variables object.

_do_add(key: str | List[str], help: str = '', default=None, validator: Callable | None = None, converter: Callable | None = None, **kwargs) None[source]#

Create a Variable and add it to the list.

This is the internal implementation for Add() and AddVariables(). Not part of the public API.

New in version 4.8.0: subst keyword argument is now recognized.

aliasfmt = '\n%s: %s\n    default: %s\n    actual: %s\n    aliases: %s\n'#
fmt = '\n%s: %s\n    default: %s\n    actual: %s\n'#
keys() list[source]#

Return the variable names.

Submodules#

SCons.Variables.BoolVariable module#

Variable type for true/false Variables.

Usage example:

opts = Variables()
opts.Add(BoolVariable('embedded', 'build for an embedded system', False))
env = Environment(variables=opts)
if env['embedded']:
    ...
SCons.Variables.BoolVariable.BoolVariable(key, help: str, default) Tuple[str, str, str, Callable, Callable][source]#

Return a tuple describing a boolean SCons Variable.

The input parameters describe a boolean variable, using a string value as described by TRUE_STRINGS and FALSE_STRINGS. Returns a tuple including the correct converter and validator. The help text will have (yes|no) automatically appended to show the valid values. The result is usable as input to Add().

SCons.Variables.BoolVariable._text2bool(val: str) bool[source]#

Convert boolean-like string to boolean.

If val looks like it expresses a bool-like value, based on the TRUE_STRINGS and FALSE_STRINGS tuples, return the appropriate value.

This is usable as a converter function for SCons Variables.

Raises:

ValueError – if val cannot be converted to boolean.

SCons.Variables.BoolVariable._validator(key, val, env) None[source]#

Validate that the value of key in env is a boolean.

Parameter val is not used in the check.

Usable as a validator function for SCons Variables.

Raises:
  • KeyError – if key is not set in env

  • UserError – if the value of key is not True or False.

SCons.Variables.EnumVariable module#

Variable type for enumeration Variables.

Enumeration variables allow selection of one from a specified set of values.

Usage example:

opts = Variables()
opts.Add(
    EnumVariable(
        'debug',
        help='debug output and symbols',
        default='no',
        allowed_values=('yes', 'no', 'full'),
        map={},
        ignorecase=2,
    )
)
env = Environment(variables=opts)
if env['debug'] == 'full':
    ...
SCons.Variables.EnumVariable.EnumVariable(key, help: str, default: str, allowed_values: List[str], map: dict | None = None, ignorecase: int = 0) Tuple[str, str, str, Callable, Callable][source]#

Return a tuple describing an enumaration SCons Variable.

The input parameters describe a variable with only predefined values allowed. The value of ignorecase defines the behavior of the validator and converter: if 0, the validator/converter are case-sensitive; if 1, the validator/converter are case-insensitive; if 2, the validator/converter are case-insensitive and the converted value will always be lower-case.

Parameters:
  • key – variable name, passed directly through to the return tuple.

  • default – default values, passed directly through to the return tuple.

  • help – descriptive part of the help text, will have the allowed values automatically appended.

  • allowed_values – list of the allowed values for this variable.

  • map – optional dictionary which may be used for converting the input value into canonical values (e.g. for aliases).

  • ignorecase – defines the behavior of the validator and converter.

Returns:

A tuple including an appropriate converter and validator. The result is usable as input to Add(). and AddVariables().

SCons.Variables.EnumVariable._validator(key, val, env, vals) None[source]#

Validate that val is in vals.

Usable as the base for EnumVariable validators.

SCons.Variables.ListVariable module#

Variable type for List Variables.

A list variable allows selecting one or more from a supplied set of allowable values, as well as from an optional mapping of alternate names (such as aliases and abbreviations) and the special names 'all' and 'none'. Specified values are converted during processing into values only from the allowable values set.

Usage example:

list_of_libs = Split('x11 gl qt ical')

opts = Variables()
opts.Add(
    ListVariable(
        'shared',
        help='libraries to build as shared libraries',
        default='all',
        elems=list_of_libs,
    )
)
env = Environment(variables=opts)
for lib in list_of_libs:
    if lib in env['shared']:
        env.SharedObject(...)
    else:
        env.Object(...)
SCons.Variables.ListVariable.ListVariable(key, help: str, default: str | List[str], names: List[str], map: dict | None = None, validator: Callable | None = None) Tuple[str, str, str, None, Callable][source]#

Return a tuple describing a list variable.

The input parameters describe a list variable, where the values can be one or more from names plus the special values all and none.

Parameters:
  • key – the name of the list variable.

  • help – the basic help message. Will have text appended indicating the allowable values (not including any extra names from map).

  • default – the default value(s) for the list variable. Can be given as string (possibly comma-separated), or as a list of strings. all or none are allowed as default. You can also simulate a must-specify ListVariable by giving a default that is not part of names, it will fail validation if not supplied.

  • names – the allowable values. Must be a list of strings.

  • map – optional dictionary to map alternative names to the ones in names, providing a form of alias. The converter will make the replacement, names from map are not stored and will not appear in the help message.

  • validator – optional callback to validate supplied values. The default validator is used if not specified.

Returns:

A tuple including the correct converter and validator. The result is usable as input to Add().

Changed in version 4.8.0: The validation step was split from the converter to allow for custom validators. The validator keyword argument was added.

class SCons.Variables.ListVariable._ListVariable(initlist: list | None = None, allowedElems: list | None = None)[source]#

Bases: UserList

Internal class holding the data for a List Variable.

This is normally not directly instantiated, rather the ListVariable converter callback “converts” string input (or the default value if none) into an instance and stores it.

Parameters:
  • initlist – the list of actual values given.

  • allowedElems – the list of allowable values.

_abc_impl = <_abc._abc_data object>#
append(item)#

S.append(value) – append value to the end of the sequence

clear() None -- remove all items from S#
copy()#
count(value) integer -- return number of occurrences of value#
extend(other)#

S.extend(iterable) – extend sequence by appending elements from the iterable

index(value[, start[, stop]]) integer -- return first index of value.#

Raises ValueError if the value is not present.

Supporting start and stop arguments is optional, but recommended.

insert(i, item)#

S.insert(index, value) – insert value before index

pop([index]) item -- remove and return item at index (default last).#

Raise IndexError if list is empty or index is out of range.

prepare_to_store()[source]#
remove(item)#

S.remove(value) – remove first occurrence of value. Raise ValueError if the value is not present.

reverse()#

S.reverse() – reverse IN PLACE

sort(*args, **kwds)#
SCons.Variables.ListVariable._converter(val, allowedElems, mapdict) _ListVariable[source]#

Callback to convert list variables into a suitable form.

The arguments allowedElems and mapdict are non-standard for a Variables converter: the lambda in the ListVariable() function arranges for us to be called correctly.

SCons.Variables.ListVariable._validator(key, val, env) None[source]#

Callback to validate supplied value(s) for a ListVariable.

Validation means “is val in the allowed list”? val has been subject to substitution before the validator is called. The converter created a _ListVariable container which is stored in env after it runs; this includes the allowable elements list. Substitution makes a string made out of the values (only), so we need to fish the allowed elements list out of the environment to complete the validation.

Note that since 18b45e456, whether subst has been called is conditional on the value of the subst argument to Add(), so we have to account for possible different types of val.

Raises:

UserError – if validation failed.

New in version 4.8.0: _validator split off from _converter() with an additional check for whether val has been substituted before the call.

SCons.Variables.PackageVariable module#

Variable type for package Variables.

To be used whenever a ‘package’ may be enabled/disabled and the package path may be specified.

Given these options

x11=no   (disables X11 support)
x11=yes  (will search for the package installation dir)
x11=/usr/local/X11 (will check this path for existence)

Can be used as a replacement for autoconf’s --with-xxx=yyy

opts = Variables()
opts.Add(
    PackageVariable(
        key='x11',
        help='use X11 installed here (yes = search some places)',
        default='yes'
    )
)
env = Environment(variables=opts)
if env['x11'] is True:
    dir = ...  # search X11 in some standard places ...
    env['x11'] = dir
if env['x11']:
    ...  # build with x11 ...
SCons.Variables.PackageVariable.PackageVariable(key: str, help: str, default, searchfunc: Callable | None = None) Tuple[str, str, str, Callable, Callable][source]#

Return a tuple describing a package list SCons Variable.

The input parameters describe a ‘package list’ variable. Returns a tuple with the correct converter and validator appended. The result is usable as input to Add().

A ‘package list’ variable may either be a truthy string from ENABLE_STRINGS, a falsy string from DISABLE_STRINGS, or a pathname string. This information is appended to help using only one string each for truthy/falsy.

SCons.Variables.PackageVariable._converter(val)[source]#

Convert package variables.

Returns True or False if one of the recognized truthy or falsy values is seen, else return the value unchanged (expected to be a path string).

SCons.Variables.PackageVariable._validator(key, val, env, searchfunc) None[source]#

Validate package variable for valid path.

Checks that if a path is given as the value, that pathname actually exists.

SCons.Variables.PathVariable module#

Variable type for path Variables.

To be used whenever a user-specified path override setting should be allowed.

Arguments to PathVariable are:
  • key - name of this variable on the command line (e.g. “prefix”)

  • help - help string for variable

  • default - default value for this variable

  • validator - [optional] validator for variable value. Predefined are:

    • PathAccept - accepts any path setting; no validation

    • PathIsDir - path must be an existing directory

    • PathIsDirCreate - path must be a dir; will create

    • PathIsFile - path must be a file

    • PathExists - path must exist (any type) [default]

The validator is a function that is called and which should return True or False to indicate if the path is valid. The arguments to the validator function are: (key, val, env). key is the name of the variable, val is the path specified for the variable, and env is the environment to which the Variables have been added.

Usage example:

opts = Variables()
opts.Add(
    PathVariable(
        'qtdir',
        help='where the root of Qt is installed',
        default=qtdir,
        validator=PathIsDir,
    )
)
opts.Add(
    PathVariable(
        'qt_includes',
        help='where the Qt includes are installed',
        default='$qtdir/includes',
        validator=PathIsDirCreate,
    )
)
opts.Add(
    PathVariable(
        'qt_libraries',
        help='where the Qt library is installed',
        default='$qtdir/lib',
    )
)
class SCons.Variables.PathVariable._PathVariableClass[source]#

Bases: object

Class implementing path variables.

This class exists mainly to expose the validators without code having to import the names: they will appear as methods of PathVariable, a statically created instance of this class, which is placed in the SConscript namespace.

Instances are callable to produce a suitable variable tuple.

static PathAccept(key, val, env) None[source]#

Validate path with no checking.

static PathExists(key, val, env) None[source]#

Validate path exists.

static PathIsDir(key, val, env) None[source]#

Validate path is a directory.

static PathIsDirCreate(key, val, env) None[source]#

Validate path is a directory, creating if needed.

static PathIsFile(key, val, env) None[source]#

Validate path is a file.

__call__(key: str, help: str, default, validator: Callable | None = None) Tuple[str, str, str, Callable, None][source]#

Return a tuple describing a path list SCons Variable.

The input parameters describe a ‘path list’ variable. Returns a tuple with the correct converter and validator appended. The result is usable for input to Add().

The default parameter specifies the default path to use if the user does not specify an override with this variable.

validator is a validator, see this file for examples