nunavut.lang.py

Filters for generating python. All filters in this module will be available in the template’s global namespace as py.

class nunavut.lang.py.Language(language_module: module, config: nunavut.lang._config.LanguageConfig, omit_serialization_support: bool, language_options: Optional[Mapping[str, Any]] = None)[source]

Bases: nunavut.lang.Language

Concrete, Python-specific nunavut.lang.Language object.

PYTHON_RESERVED_IDENTIFIERS = ['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'None', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'ZeroDivisionError', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'all', 'and', 'any', 'as', 'ascii', 'assert', 'async', 'await', 'bin', 'bool', 'break', 'breakpoint', 'bytearray', 'bytes', 'callable', 'chr', 'class', 'classmethod', 'compile', 'complex', 'continue', 'copyright', 'credits', 'def', 'del', 'delattr', 'dict', 'dir', 'divmod', 'elif', 'else', 'enumerate', 'eval', 'except', 'exec', 'exit', 'filter', 'finally', 'float', 'for', 'format', 'from', 'frozenset', 'getattr', 'global', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'if', 'import', 'in', 'input', 'int', 'is', 'isinstance', 'issubclass', 'iter', 'lambda', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'nonlocal', 'not', 'object', 'oct', 'open', 'or', 'ord', 'pass', 'pow', 'print', 'property', 'quit', 'raise', 'range', 'repr', 'return', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'try', 'tuple', 'type', 'vars', 'while', 'with', 'yield', 'zip']
get_includes(dep_types: nunavut.dependencies.Dependencies) → List[str][source]

Get a list of include paths that are specific to this language and the options set for it. :param Dependencies dep_types: A description of the dependencies includes are needed for. :return: A list of include file paths. The list may be empty if no includes were needed.

filter_id(instance: Any, id_type: str = 'any') → str[source]

Produces a valid identifier in the language for a given object. The encoding may not be reversible.

Parameters:
  • instance (any) – Any object or data that either has a name property or can be converted to a string.
  • id_type (str) – A type of identifier. This is different for each language. For example, for C this value can be ‘typedef’, ‘macro’, ‘function’, or ‘enum’. Use ‘any’ to apply stropping rules for all identifier types to the instance.
Returns:

A token that is a valid identifier in the language, is not a reserved keyword, and is transformed in a deterministic manner based on the provided instance.

nunavut.lang.py.filter_to_template_unique_name(context: nunavut.templates.SupportsTemplateContext, base_token: str) → str[source]

Filter that takes a base token and forms a name that is very likely to be unique within the template the filter is invoked. This name is also very likely to be a valid Python identifier.

Important

The exact tokens generated may change between major or minor versions of this library. The only guarantee provided is that the tokens will be stable for the same version of this library given the same input.

Also note that name uniqueness is only likely within a given template. Between templates there is no guarantee of uniqueness and, since this library does not lex generated source, there is no guarantee that the generated name does not conflict with a name generated by another means.

# Given
template  = '{{ "f" | to_template_unique_name }},{{ "f" | to_template_unique_name }},'
template += '{{ "f" | to_template_unique_name }},{{ "bar" | to_template_unique_name }}'

# then
rendered = '_f0_,_f1_,_f2_,_bar0_'
# Given
template = '{{ "i like coffee" | to_template_unique_name }}'

# then
rendered = '_i like coffee0_'
Parameters:base_token (str) – A token to include in the base name.
Returns:A name that is likely to be valid python identifier and is likely to be unique within the file generated by the current template.
nunavut.lang.py.filter_id(language: nunavut.lang.py.Language, instance: Any, id_type: str = 'any') → str[source]

Filter that produces a valid Python identifier for a given object. The encoding may not be reversible.

# Given
I = 'I like python'

# and
template = '{{ I | id }}'

# then
rendered = 'I_like_python'
# Given
I = '&because'

# and
template = '{{ I | id }}'

# then
rendered = 'zX0026because'
# Given
I = 'if'

# and
template = '{{ I | id }}'

# then
rendered = 'if_'
Parameters:instance (any) – Any object or data that either has a name property or can be converted to a string.
Returns:A token that is a valid Python identifier, is not a reserved keyword, and is transformed in a deterministic manner based on the provided instance.
nunavut.lang.py.filter_full_reference_name(language: nunavut.lang.py.Language, t: pydsdl._serializable._composite.CompositeType) → str[source]

Provides a string that is the full namespace, typename, major, and minor version for a given composite type.

# Given
full_name = 'any.str.2Foo'
major = 1
minor = 2

# and
template = '{{ my_obj | full_reference_name }}'

# then
rendered = 'any_.str_.zX0032Foo_1_2'
Parameters:t (pydsdl.CompositeType) – The DSDL type to get the fully-resolved reference name for.
nunavut.lang.py.filter_short_reference_name(language: nunavut.lang.py.Language, t: pydsdl._serializable._composite.CompositeType) → str[source]

Provides a string that is a shorted version of the full reference name. This type is unique only within its namespace.

# Given
short_name = '2Foo'
major = 1
minor = 2

# and
template = '{{ my_obj | short_reference_name }}'

# then
rendered = 'zX0032Foo_1_2'
Parameters:t (pydsdl.CompositeType) – The DSDL type to get the reference name for.
nunavut.lang.py.filter_imports(language: nunavut.lang.py.Language, t: pydsdl._serializable._composite.CompositeType, sort: bool = True) → List[str][source]

Returns a list of all modules that must be imported to use a given type.

Parameters:
  • t (pydsdl.CompositeType) – The type to scan for dependencies.
  • sort (bool) – If true the returned list will be sorted.
Returns:

a list of python module names the provided type depends on.

nunavut.lang.py.filter_longest_id_length(language: nunavut.lang.py.Language, attributes: List[pydsdl._serializable._attribute.Attribute]) → int[source]

Return the length of the longest identifier in a list of pydsdl.Attribute objects.

# Given
I = ['one.str.int.any', 'three.str.int.any']

# and
template = '{{ I | longest_id_length }}'

# then
rendered = '32'