Skip to content

Commit

Permalink
Merge pull request #303 from robshakir/python_updates
Browse files Browse the repository at this point in the history
Python version and linter updates
  • Loading branch information
JoseIgnacioTamayo authored Jul 22, 2023
2 parents f549009 + 03f4071 commit 9b00586
Show file tree
Hide file tree
Showing 26 changed files with 139 additions and 177 deletions.
2 changes: 0 additions & 2 deletions pyangbind/helpers/identity.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@


class Identity(object):

def __init__(self, name):
self.name = name
self.source_module = None
Expand All @@ -47,7 +46,6 @@ def prefixes(self):


class IdentityStore(object):

def __init__(self):
self._store = []

Expand Down
3 changes: 0 additions & 3 deletions pyangbind/lib/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@


class PybindBase(object):

__slots__ = ()

def elements(self):
Expand All @@ -30,7 +29,6 @@ def __str__(self):
return str(self.elements())

def get(self, filter=False):

def error():
return NameError, "element does not exist"

Expand Down Expand Up @@ -100,7 +98,6 @@ def error():
return d

def __getitem__(self, k):

def error():
raise KeyError("Key %s does not exist" % k)

Expand Down
1 change: 0 additions & 1 deletion pyangbind/lib/pybindJSON.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,6 @@ def load_ietf(fn, parent_pymod, yang_module, path_helper=None, extmethods=None,


def dumps(obj, indent=4, filter=True, skip_subtrees=[], select=False, mode="default", with_defaults=None):

def lookup_subdict(dictionary, key):
if not isinstance(key, list):
raise AttributeError("keys should be a list")
Expand Down
7 changes: 4 additions & 3 deletions pyangbind/lib/serialise.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ class pybindJSONDecodeError(Exception):

class UnmappedItem(Exception):
"""Used to simulate an Optional value"""

pass


Expand Down Expand Up @@ -266,6 +267,7 @@ class _pybindJSONEncoderBase(json.JSONEncoder):
Do not use directly, subclass and set the `serialiser_class` attribute appropriately
"""

serialiser_class = None

def encode(self, obj):
Expand All @@ -277,12 +279,14 @@ def default(self, obj):

class pybindJSONEncoder(_pybindJSONEncoderBase):
"""Default pybind JSON encoder"""

serialiser_class = YangDataSerialiser


class pybindIETFJSONEncoder(_pybindJSONEncoderBase):
"""IETF JSON encoder, we add a special method `generate_element()` that should be used
to restructure the pybind object to fit IETF requirements prior to JSON encoding."""

serialiser_class = IETFYangDataSerialiser

@staticmethod
Expand Down Expand Up @@ -492,7 +496,6 @@ def load_xml(d, parent, yang_base, obj=None, path_helper=None, extmethods=None):
chobj = attr_get()

if chobj._yang_type == "container":

if hasattr(chobj, "_presence"):
if chobj._presence:
chobj._set_present()
Expand Down Expand Up @@ -563,12 +566,10 @@ def load_xml(d, parent, yang_base, obj=None, path_helper=None, extmethods=None):


class pybindJSONDecoder(object):

@staticmethod
def load_json(
d, parent, yang_base, obj=None, path_helper=None, extmethods=None, overwrite=False, skip_unknown=False
):

if obj is None:
# we need to find the class to create, as one has not been supplied.
base_mod_cls = getattr(parent, safe_name(yang_base))
Expand Down
51 changes: 25 additions & 26 deletions pyangbind/lib/xpathhelper.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,49 +49,48 @@ class PybindImplementationError(Exception):


class PybindXpathHelper(object):

def register(self, path, object_ptr, caller=False):
"""
A PybindXpathHelper class should supply a register() method that
takes two mandatory arguments, and one optional.
A PybindXpathHelper class should supply a register() method that
takes two mandatory arguments, and one optional.
* path - the path to which the object should be registered. This is
supplied as a list of the names of the elements of the path. For
example, /device/interfaces/interface[name='eth0'] is supplied as
a ["device", "interfaces", "interface[@name='eth0']"].
* path - the path to which the object should be registered. This is
supplied as a list of the names of the elements of the path. For
example, /device/interfaces/interface[name='eth0'] is supplied as
a ["device", "interfaces", "interface[@name='eth0']"].
* object_ptr - a reference to the object that is to be stored at this
location in the tree.
* object_ptr - a reference to the object that is to be stored at this
location in the tree.
* caller=False - this supplies the path of the object that is currently
trying to perform a register. In general, it will not be used, but it
is supplied to facilitate relative path lookups.
"""
* caller=False - this supplies the path of the object that is currently
trying to perform a register. In general, it will not be used, but it
is supplied to facilitate relative path lookups.
"""
raise PybindImplementationError("The path helper class specified does " + "not implement register()")

def unregister(self, path, caller=False):
"""
A PybindXpathHelper class should supply an unregister() method that
takes one mandatory argument, and one optional.
A PybindXpathHelper class should supply an unregister() method that
takes one mandatory argument, and one optional.
* path - the path of the object to be unregistered. Supplied as a list()
object of the elements of the path.
* path - the path of the object to be unregistered. Supplied as a list()
object of the elements of the path.
* caller=False - the absolute path of the object calling the unregister()
method.
"""
* caller=False - the absolute path of the object calling the unregister()
method.
"""
raise PybindImplementationError("The path helper class specified does " + "not implement unregister()")

def get(self, path, caller=False):
"""
A PybindXpathHelper class should supply a get() method that takes one
mandatory argument and one optional.
A PybindXpathHelper class should supply a get() method that takes one
mandatory argument and one optional.
* path - the path to the object to be retrieved. This may be specified as
a list of parts, or an XPATH expression.
* path - the path to the object to be retrieved. This may be specified as
a list of parts, or an XPATH expression.
* caller=False - the absolute path of the object calling the get method.
"""
* caller=False - the absolute path of the object calling the get method.
"""
raise PybindImplementationError("The path helper class specified does " + "not implement get()")


Expand Down
65 changes: 31 additions & 34 deletions pyangbind/lib/yangtypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ def remove_path_attributes(p):
def safe_name(arg):
"""
Make a leaf or container name safe for use in Python.
"""
"""
arg = arg.replace("-", "_")
arg = arg.replace(".", "_")
if arg in reserved_name:
Expand All @@ -134,23 +134,24 @@ def RestrictedPrecisionDecimalType(*args, **kwargs):
"""
Function to return a new type that is based on decimal.Decimal with
an arbitrary restricted precision.
"""
"""
precision = kwargs.pop("precision", False)

class RestrictedPrecisionDecimal(Decimal):
"""
Class extending decimal.Decimal to restrict the precision that is
stored, supporting the fraction-digits argument of the YANG decimal64
type.
"""
Class extending decimal.Decimal to restrict the precision that is
stored, supporting the fraction-digits argument of the YANG decimal64
type.
"""

_precision = 10.0 ** (-1.0 * int(precision))
_pybind_generated_by = "RestrictedPrecisionDecimal"

def __new__(self, *args, **kwargs):
"""
Overloads the decimal __new__ function in order to round the input
value to the new value.
"""
Overloads the decimal __new__ function in order to round the input
value to the new value.
"""
if self._precision is not None:
if len(args):
value = Decimal(args[0]).quantize(Decimal(str(self._precision)))
Expand All @@ -172,7 +173,7 @@ def RestrictedClassType(*args, **kwargs):
a specified restriction. The restriction_type specified determines the
type of restriction placed on the class, and the restriction_arg gives
any input data that this function needs.
"""
"""
base_type = kwargs.pop("base_type", six.text_type)
restriction_type = kwargs.pop("restriction_type", None)
restriction_arg = kwargs.pop("restriction_arg", None)
Expand All @@ -191,21 +192,22 @@ def RestrictedClassType(*args, **kwargs):

class RestrictedClass(base_type):
"""
A class that restricts the base_type class with a new function that the
input value is validated against before being applied. The function is
a static method which is assigned to _restricted_test.
"""
A class that restricts the base_type class with a new function that the
input value is validated against before being applied. The function is
a static method which is assigned to _restricted_test.
"""

_pybind_generated_by = "RestrictedClassType"

_restricted_class_base = restricted_class_hint
_restricted_int_size = int_size

def __init__(self, *args, **kwargs):
"""
Overloads the base_class __init__ method to check the input argument
against the validation function - returns on instance of the base_type
class, which can be manipulated as per a usual Python object.
"""
Overloads the base_class __init__ method to check the input argument
against the validation function - returns on instance of the base_type
class, which can be manipulated as per a usual Python object.
"""
try:
self.__check(args[0])
except IndexError:
Expand All @@ -228,7 +230,6 @@ def __new__(self, *args, **kwargs):
range_single_value_regex = regex.compile("(?P<value>\-?[0-9\.]+)")

def convert_regexp(pattern):

# Some patterns include a $ character in them in some IANA modules, this
# is not escaped. Do some logic to escape them, whilst leaving one at the
# end of the string if it's there.
Expand Down Expand Up @@ -271,7 +272,6 @@ def build_length_range_tuples(range, length=False, multiplier=1):
raise ValueError("Invalid range or length argument specified")

def in_range_check(low_high_tuples, length=False):

def range_check(value):
if length and isinstance(value, bitarray):
value = value.length()
Expand All @@ -296,7 +296,6 @@ def range_check(value):
return range_check

def match_pattern_check(regexp):

def mp_check(value):
if not isinstance(value, six.string_types + (six.text_type,)):
return False
Expand Down Expand Up @@ -383,9 +382,9 @@ def in_dictionary_check(dictionary):

def __check(self, v):
"""
Run the _restriction_test static method against the argument v,
returning an error if the value does not validate.
"""
Run the _restriction_test static method against the argument v,
returning an error if the value does not validate.
"""
v = base_type(v)
for chkfn in self._restriction_tests:
if not chkfn(v):
Expand All @@ -394,9 +393,9 @@ def __check(self, v):

def getValue(self, *args, **kwargs):
"""
For types where there is a dict_key restriction (such as YANG
enumeration), return the value of the dictionary key.
"""
For types where there is a dict_key restriction (such as YANG
enumeration), return the value of the dictionary key.
"""
if "dict_key" in self._restriction_dict:
value = kwargs.pop("mapped", False)
if value:
Expand All @@ -411,7 +410,7 @@ def TypedListType(*args, **kwargs):
Return a type that consists of a list object where only
certain types (specified by allowed_type kwarg to the function)
can be added to the list.
"""
"""
allowed_type = kwargs.pop("allowed_type", six.text_type)
if not isinstance(allowed_type, list):
allowed_type = [allowed_type]
Expand Down Expand Up @@ -538,7 +537,7 @@ def YANGListType(*args, **kwargs):
Where a list exists that does not have a key - which can be the
case for 'config false' lists - a uuid is generated and used
as the key for the list.
"""
"""
try:
keyname = args[0]
listclass = args[1]
Expand Down Expand Up @@ -888,7 +887,7 @@ class YANGBool(int):
This bool also accepts input matching strings to handle the
forms that might be used in YANG modules.
"""
"""

def __new__(self, *args, **kwargs):
false_args = ["false", "False", False, 0, "0"]
Expand Down Expand Up @@ -935,7 +934,7 @@ def YANGDynClass(*args, **kwargs):
node.
- presence: Whether the YANG container that is being
represented has the presence keyword
"""
"""
base_type = kwargs.pop("base", False)
default = kwargs.pop("default", False)
yang_name = kwargs.pop("yang_name", False)
Expand Down Expand Up @@ -1198,7 +1197,6 @@ def _register_path(self):
return []

def __generate_extmethod(self, methodfn):

def extmethodfn(*args, **kwargs):
kwargs["caller"] = self._register_path()
kwargs["path_helper"] = self._path_helper
Expand Down Expand Up @@ -1232,14 +1230,13 @@ def ReferenceType(*args, **kwargs):
to be a relative (rather than absolute) path. The require_instance
argument specifies whether errors should be thrown in the case
that the referenced instance does not exist.
"""
"""
ref_path = kwargs.pop("referenced_path", False)
path_helper = kwargs.pop("path_helper", None)
caller = kwargs.pop("caller", False)
require_instance = kwargs.pop("require_instance", False)

class ReferencePathType(object):

__slots__ = (
"_referenced_path",
"_path_helper",
Expand Down
3 changes: 0 additions & 3 deletions pyangbind/plugin/pybind.py
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,6 @@ def pyang_plugin_init():


class PyangBindClass(plugin.PyangPlugin):

def add_output_format(self, fmts):
# Add the 'pybind' output format to pyang.
self.multiple_modules = True
Expand Down Expand Up @@ -619,7 +618,6 @@ def build_typedefs(ctx, defnd):
parent_type = []
default = False if default_stmt is None else default_stmt.arg
for i in elemtype:

if isinstance(i[1]["native_type"], list):
native_type.extend(i[1]["native_type"])
else:
Expand Down Expand Up @@ -648,7 +646,6 @@ def build_typedefs(ctx, defnd):


def get_children(ctx, fd, i_children, module, parent, path=str(), parent_cfg=True, choice=False, register_paths=True):

# Iterative function that is called for all elements that have childen
# data nodes in the tree. This function resolves those nodes into the
# relevant leaf, or container/list configuration and outputs the python
Expand Down
Loading

0 comments on commit 9b00586

Please sign in to comment.