rez.utils.formatting

Utilities related to formatting output or translating input.

rez.utils.formatting.is_valid_package_name(name: str, raise_error: bool = False) bool

Test the validity of a package name string.

Parameters:
  • name (str) – Name to test.

  • raise_error (bool) – If True, raise an exception on failure

Returns:

bool.

class rez.utils.formatting.PackageRequest

Bases: Requirement

A package request parser.

Valid requests include:

  • Any standard request, eg ‘foo-1.2.3’, ‘!foo-1’, etc

  • “Ephemeral” request, eg ‘.foo-1.2.3’

Example

>>> pr = PackageRequest("foo-1.3+")
>>> print(pr.name, pr.range)
foo 1.3+
__init__(s: str) None
Parameters:
  • s (str) – Requirement string

  • invalid_bound_error (bool) – If True, raise VersionError if an impossible range is given, such as 3+<2.

property conflict: bool

True if the requirement is a conflict requirement, eg “!foo”, “~foo-1”.

Return type:

bool

conflicts_with(other: Requirement | VersionedObject) bool

Returns True if this requirement conflicts with another Requirement or VersionedObject.

Return type:

bool

classmethod construct(name: str, range: VersionRange | None = None) Requirement

Create a requirement directly from an object name and VersionRange.

Parameters:
  • name (str) – Object name string.

  • range (Optional[VersionRange]) – If None, an unversioned requirement is created.

merged(other: Requirement) Requirement | None

Merge two requirements.

Two requirements can be in conflict and if so, this function returns None. For example, requests for foo-4 and foo-6 are in conflict, since both cannot be satisfied with a single version of foo.

Some example successful requirements merges are:

  • foo-3+ and !foo-5+ == foo-3+<5

  • foo-1 and foo-1.5 == foo-1.5

  • !foo-2 and !foo-5 == !foo-2|5

Returns:

the merged result of two requirements.

Return type:

Requirement

property name: str

Name of the required object.

Return type:

str

property range: VersionRange

Version range of the requirement.

Return type:

VersionRange

safe_str() str

Return a string representation that is safe for the current filesystem, and guarantees that no two different Requirement objects will encode to the same value.

Return type:

str

sep_regex = re.compile('[-@#=<>]')
property weak: bool

True if the requirement is weak, eg “~foo”.

Note

Note that weak requirements are also conflict requirements, but not necessarily the other way around.

Return type:

bool

class rez.utils.formatting.StringFormatType

Bases: Enum

Behaviour of key expansion when using ObjectStringFormatter.

error = 1
empty = 2
unchanged = 3
class rez.utils.formatting.ObjectStringFormatter

Bases: Formatter

String formatter for objects.

This formatter will expand any reference to an object’s attributes.

error = 1
empty = 2
unchanged = 3
__init__(instance: Any, pretty: bool = False, expand: StringFormatType = StringFormatType.error) None

Create a formatter.

Parameters:
  • instance – The object to format with.

  • pretty – If True, references to non-string attributes such as lists are converted to basic form, with characters such as brackets and parentheses removed.

  • expandStringFormatType.

convert_field(value: Any, conversion: str | None) Any
get_field(field_name: str, args: Sequence[Any], kwargs: Mapping[str, Any]) Any
get_value(key: int | str, args: Sequence[Any], kwds: Mapping[str, Any]) Any
check_unused_args(used_args, args, kwargs)
format(format_string, /, *args, **kwargs)
format_field(value, format_spec)
parse(format_string)
vformat(format_string, args, kwargs)
class rez.utils.formatting.StringFormatMixin

Bases: object

Turn any object into a string formatter.

An object inheriting this mixin will have a format function added, that is able to format using attributes of the object.

format_expand = 1
format_pretty = True
format(s: str, pretty: bool | None = None, expand: StringFormatType | None = None) str

Format a string.

Parameters:
  • s (str) – String to format, eg “hello {name}”

  • pretty (bool) – If True, references to non-string attributes such as lists are converted to basic form, with characters such as brackets and parenthesis removed. If None, defaults to the object’s ‘format_pretty’ attribute.

  • expand (StringFormatType) – Expansion mode. If None, will default to the object’s ‘format_expand’ attribute.

Returns:

The formatting string.

rez.utils.formatting.expand_abbreviations(txt: str, fields: list[str]) str

Expand abbreviations in a format string.

If an abbreviation does not match a field, or matches multiple fields, it is left unchanged.

Example

>>> fields = ("hey", "there", "dude")
>>> expand_abbreviations("hello {d}", fields)
'hello dude'
Parameters:
  • txt (str) – Format string.

  • fields (list of str) – Fields to expand to.

Returns:

Expanded string.

rez.utils.formatting.expandvars(text: str, environ: Mapping[str, str] | None = None) str

Expand shell variables of form $var and ${var}.

Unknown variables are left unchanged.

Parameters:
  • text (str) – String to expand.

  • environ (dict) – Environ dict to use for expansions, defaults to os.environ.

Returns:

The expanded string.

rez.utils.formatting.indent(txt: str) str

Indent the given text by 4 spaces.

rez.utils.formatting.dict_to_attributes_code(dict_: dict) str

Given a nested dict, generate a python code equivalent.

Example

>>> d = {'foo': 'bah', 'colors': {'red': 1, 'blue': 2}}
>>> print(dict_to_attributes_code(d))
foo = 'bah'
colors.red = 1
colors.blue = 2
Returns:

str.

rez.utils.formatting.columnise(rows: Sequence[Sequence[Any]], padding: int = 2) list[str]

Print rows of entries in aligned columns.

rez.utils.formatting.print_colored_columns(printer: colorize.Printer, rows: Sequence[tuple], padding: int = 2) None

Like columnise, but with colored rows.

Parameters:

printer (colorize.Printer) – Printer object.

Note

The last entry in each row is the row color, or None for no coloring.

rez.utils.formatting.readable_time_duration(secs: int) str

Convert number of seconds into human readable form, eg ‘3.2 hours’.

rez.utils.formatting.readable_memory_size(bytes_: int) str

Convert number of bytes into human-readable form.

This method rounds to 1 decimal place eg ‘1.2 Kb’.

rez.utils.formatting.get_epoch_time_from_str(s: str) int

Convert a string into epoch time. Examples of valid strings:

1418350671 # already epoch time -12s # 12 seconds ago -5.4m # 5.4 minutes ago

rez.utils.formatting.positional_number_string(n: int) str

Print the position string equivalent of a positive integer. Examples:

0: zeroeth 1: first 2: second 14: 14th 21: 21st

rez.utils.formatting.expanduser(path: str) str

Expand ‘~’ to home directory in the given string.

Note that this function deliberately differs from the builtin os.path.expanduser() on Linux systems, which expands strings such as ‘~sclaus’ to that user’s homedir. This is problematic in rez because the string ‘~packagename’ may inadvertently convert to a homedir, if a package happens to match a username.

rez.utils.formatting.as_block_string(txt: str) str

Return a string formatted as a python block comment string, like the one you’re currently reading. Special characters are escaped if necessary.

rez.utils.formatting.header_comment(executor: RexExecutor, txt: str) None

Convenience for creating header-like comment in a rex executor.

Parameters:
  • executor (RexExecutor) – Executor.

  • txt (str) – Comment text.

rez.utils.formatting.minor_header_comment(executor: RexExecutor, txt: str) None