API Docs¶
Submodules¶
- class genie.abstract.decorator.LookupDecorator(*attrs)¶
Bases:
object
This class is to be used as a decorator on class methods in abstracted packages. It allows dynamic class method references: eg, calling obj.b() first performs a lookup on the tokens, and if found, calls the class.b from the actual token matching.
This class is built on the python descriptor mechanism.
Note
This class functions based on the same principles as the AbstractPackage and Lookup() combination. However, instead of using declare_package() at the root of an abstraction package. this decorator treats the calling class’s module as the root of a new abstraction package, and goes from there.
Examples
class MyClass(object):
@LookupDecorator(‘os’) def do_work(self):
pass
- Parameters
*attrs (function to decorate, or deprecated arguments for abstract order) –
- from_device¶
- genie.abstract.magic.recursive_update_extend(a, b)¶
recursive_update
Recursively updates on nested dictionary a with dictionary b, but creates or extends a list if there is a conflict instead of overwriting. The list will have elements of b before the elements of a, and any duplicate values removed.
- genie.abstract.magic.ensure_list(a)¶
- genie.abstract.magic.get_caller_stack_pkgs(stacklvl=1)¶
helper function, returns a dictionary of names/abstraction module based on the caller’s stack frame.
Example
>>> import genie >>> import mylib as local_lib >>> get_caller_stack_pkgs() {'genie': <module genie...>, 'local_lib': <module mylib...>,}
- class genie.abstract.magic.LookupWrapper(*tokens, device=None, packages=None)¶
Bases:
object
Contains multiple Lookup object since each one now only contains a single package, to differentiate between package specific tokens.
- Parameters
(dict) (packages) –
- class genie.abstract.magic.Lookup(*args, **kwargs)¶
Bases:
object
When instanciated with a set of “token requirements”, the lookup object allows users to dynamically reference libraries (abstraction packages).
The concept is akin to dynamic imports. As opposed to
>>> from genie.nxos import Ospf >>> from local_lib.nxos.titanium import Blah
lookup allows the user to simply do:
>>> import genie >>> import local_lib >>> l = Lookup('nxos', 'titanium') >>> l.Ospf() >>> l.Blah()
where the actual import based on the given tokens will be sorted out for the user dynamically.
- Parameters
(dict) (packages) –
(dict) – if not provided, the caller’s stack is looked up for all available abstraction packages.
Examples
>>> import my_abstracted_lib as lib >>> l = Lookup('nxos', 'titanium') >>> l.lib.module_a.module_b.MyClass()
- classmethod from_device(device, packages=None, **kwargs)¶
creates an abstraction Lookup object by getting the token arguments from a pyATS device objects.
This api expects the device object to have an “abstraction” dictionary under ‘custom’ attribute. Eg:
Example
- devices:
- my-device:
os: nxos platform: n7k custom:
- abstraction:
platform: n9k # additional override
- Parameters
(Device) (device) –
(dict) (packages) – if not provided, the caller’s stack is looked up for all available abstraction packages.
(kwargs) (**kwargs) –
- classmethod tokens_from_device(device: Device, token_attrs: list[str], package: str = None) → dict[str, str]¶
Gather tokens from device
- Parameters
device (Device) – Device object to gather tokens from
token_attrs (list[str]) – List of token attributes to gather from the device
package (str, optional) – Package to attempt to import and update tokens from, by default None
- Returns
Dict of tokens gathered from the device
- Return type
dict[str, str]
- class genie.abstract.magic.AbstractedModule(package: AbstractPackage, tokens: Dict[str, str])¶
Bases:
object
Internal class, part-two of lookup mechanism. This class is instanciated each time a successful package reference (through Lookup class instances) is done, and tracks internally user’s attribute chain, used as part of the lookup process.
Create an AbstractedModule object
- Parameters
(AbstractPackage) (package) – the abstract package to reference
(Dict[str (tokens) – sequence of tokens to perform lookup.
str]) – sequence of tokens to perform lookup.
- property tokens¶
- class genie.abstract.package.AbstractTree(order: list[str] = None, feature: str = None, pkg: AbstractPackage = None)¶
Bases:
object
Abstract Tree, orchestrator for AbstractTreeNodes
- Parameters
order (list[str], optional) – Order of tokens to organize nodes by, by default None
- loaded_packages = {'default_revision': None, 'features': None, 'version': 1}¶
- classmethod from_json(contents: dict[str, Any], package=None, feature: str = None)¶
Class method to generate a new AbstractMatrix from one of the loaded JSON files
- class genie.abstract.package.AbstractTreeNode(parent: AbstractTreeNode, ptr: ModuleType | str = None, depth: int = - 1)¶
Bases:
object
- property token_tree: dict[str, dict]¶
- get(key: str, default: Any = None) → AbstractTreeNode | Any¶
Attempts to get a value, returns
default
if not found- Parameters
key (str) – Key to try and get
default (Any, optional) – Default value to return if not found, by default None
- Returns
Returned object
- Return type
AbstractTreeNode | Any
- get_create(key: str, ptr: ModuleType | str = None) → AbstractTreeNode¶
Like setdefault but with depth and order handling
- Parameters
key (str) – Key to try and get
ptr (ModuleType | str, optional) – Module to assign to tree node, by default None
- Returns
Created or found tree node
- Return type
- get_exact(key: str, default: Any = None) → AbstractTreeNode | Any¶
A get function that does not allow version matching with a single value, object type must also be the same.
- items() → Iterable[genie.abstract.package.AbstractTreeNode]¶
- keys() → Iterable[str]¶
- values() → Iterable[genie.abstract.package.AbstractTreeNode]¶
- iter_import_paths(path: str = '') → list[str]¶
Generates a list of importable paths from the module
- Parameters
path (str, optional) – Path to build sub-path from, by default ‘’
- Returns
A list of import paths for the module
- Return type
list[str]
- iter_lookup(tokens: dict[str, str], top: str = None, _loaded_ids: list[str] = None) → list[AbstractTreeNode]¶
yield possible matches for a ‘top’ value given a dict of tokens.
A ‘top’ value is an abstracted module path like genie.libs.parser.show_routing or a specific feature like a parser command or an API name.
- lookup(tokens: dict[str, str], top: str = None, _loaded_ids: list[str] = None) → list[AbstractTreeNode]¶
- property child_token_key: str | None¶
The token key of the layer below this node. In the past, this was incorrectly named “token_key” which cause great confusion when debugging. Eventually it was realized that this was the child node’s token key and was updated accordingly.
It’s important for us to know what the next token key in the chain will be as it allows us to create our child nodes correctly.
- Returns
The token key of the child nodes
- Return type
str | None
- property token_key: str | None¶
The token key that represents the current node. As of writing this, this property has no functional use outside of helping with debugging code
- Returns
The token key that represents this node
- Return type
str | None
- update(other: genie.abstract.package.AbstractTreeNode)¶
Recursive update from another AbstractTreeNode
- property id: str¶
- property tokens: dict[str, str]¶
- property abstract_tree¶
- property root¶
- property order: list[str]¶
- property ptr: ModuleType | str | None¶
- load_ptr() → module¶
Attempts to load the ptr string into an actual object/module to return
- property command: str¶
- property token_val: str | None¶
- property feature: str¶
- class genie.abstract.package.AbstractPackage(module, order=None, delay=False, feature=None)¶
Bases:
object
An abstract package is one where its import paths are two parth: the relative information part, and the tokenization part. With the proper tools, abstract packages allows users to make calls to classes/methods/etc without having to explicitly specify the import/module path, and only use the informational one.
- from my_library.nxos.ospf import Ospf
- | |token |
- library pkg |
information path
When an abstract package is learnt, all child modules within the given module (if it is a) package, will be loaded recursively in order to build the abstraction matrix/database. Normally this class instance is stored under a var called “__abstract_pkg” on the given module.
Note
A package is a module that contains other modules.
- Parameters
(str/ModuleType) (module) –
(list) (order) –
(bool) (delay) – module’s child modules.
- property paths¶
search paths for this package’s children modules. - if it’s a namespace package, __path__ is a list - else, default to its [__file__, ] - note: could’ve used ModuleSpec (__spec__) instead for python 3.4+
- property learnt¶
property, returns True if the matrix is not empty (learnt). Otherwise, returns false.
- property module¶
returns the python module object assoicated with this abstracted package
- learn()¶
recursively learn this package’s child content
- set_defaults(values)¶
update the default tokens for this package from lists of possible tokens values
- preceeds(token_a, token_b)¶
Ensures that a child abstract module does not define earlier tokens than are present in the parent abstract module.
- classmethod legacy_warn()¶
- register(relpath, tokens, module)¶
store a module internally with its relative name and token path in the internal matrix.
- Parameters
(str) (relpath) –
(list) (tokens) –
(ModuleType) (module) –
- lookup(relpath, tokens, name)¶
- genie.abstract.package.seen(p)¶
- genie.abstract.package.iter_packages(package)¶
Iterate through all available packages under a given package, and yield the package and the member modules separates to prevent loading every single module during discovery
- genie.abstract.package.get_relative_path(absname, token_paths)¶
- class genie.abstract.token.LegacyToken(module_name)¶
Bases:
object
- class genie.abstract.token.Version(version: str)¶
Bases:
packaging.version.Version
Initialize a Version object.
- Parameters
version – The string representation of a version which will be parsed and normalized before use.
- Raises
InvalidVersion – If the
version
does not conform to PEP 440 in any way then this exception will be raised.
- class genie.abstract.token.VersionRange(min=None, max=None)¶
Bases:
object
A class representing a range of versions. The range is inclusive on the lower bound and exclusive on the upper bound. The range is represented as min <= version < max.
The min and max values can be any valid version string, or the strings ‘-Infinity’ and ‘Infinity’ to represent negative and positive infinity, respectively. If min is None or ‘-Infinity’, it will be set to version.NegativeInfinity. If max is None or ‘Infinity’, it will be set to Infinity.
Used primarily in the abstract package to represent version ranges for Genie features. Stored in the generated JSON files.
- from_string(str):
Create a VersionRange object from a string representation.
- from_dict(dict):
Create a VersionRange object from a dictionary representation.
Create a VersionRange object.
- Parameters
min (str, optional) – Minimum version, by default None
max (str, optional) – Maximum version, by default None
- classmethod from_string(s: str) → VersionRange¶
- classmethod from_dict(d)¶
- class genie.abstract.token.AbstractToken(module: module, matches: Optional[dict] = None, legacy: Optional[genie.abstract.token.LegacyToken] = None)¶
Bases:
object
Describes an arbitrary named token within an abstracted package. Normally this class instance is stored under a var called “__abstract_token” on the given module.
- moduleModuleType
Loaded python module object
Create an AbstractToken object.
- Parameters
module (ModuleType) – Python module object
matches (dict, optional) – A dict of key/values representing the token name and token value respectively, by default None
legacy (LegacyToken, optional) – A legacy token to fallback to, by default None
- property module¶
returns the python module object assoicated with this token
- class genie.abstract.token.TokenChain(chain=None)¶
Bases:
object
Internal class. Used to track the current chain of tokens in the recursive import process.
- Parameters
(list) (chain) –
- track(module)¶
context manager api allowing auto-tracking of tokens using the with statement. On entry, stors the discovered token (if any) internally, on exit, removes that token from tracking.
- Parameters
(ModuleType) (module) –
Example
>>> with tokenchain.track(module): ... pass
- property latest¶
- to_tuple()¶
to_tuples
returns all currently tracked tokens in a tuple. This is needed as the abstracted package uses token tuples as keys for lookup.
- copy()¶