From 88821300e0b775cc07303402f3d7dcdf6e6192ae Mon Sep 17 00:00:00 2001 From: Jesper Friis Date: Sun, 13 Aug 2023 12:06:41 +0200 Subject: [PATCH] Reverting some bad formatting and code that was unfortunately introduced. --- bindings/python/dlite-entity-python.i | 3 +- bindings/python/dlite-entity.i | 13 ++-- bindings/python/dlite-misc-python.i | 8 +-- bindings/python/dlite-misc.i | 36 +++++----- bindings/python/dlite-python.i | 1 + bindings/python/dlite-storage.i | 20 ++---- bindings/python/factory.py | 94 +++++++++++++-------------- bindings/python/mappings.py | 59 ++++++++--------- 8 files changed, 114 insertions(+), 120 deletions(-) diff --git a/bindings/python/dlite-entity-python.i b/bindings/python/dlite-entity-python.i index 23c0bd25e..94d3ebfc2 100644 --- a/bindings/python/dlite-entity-python.i +++ b/bindings/python/dlite-entity-python.i @@ -92,7 +92,7 @@ def standardise(v, prop, asdict=False): return conv(v) -def get_instance(id: "str", metaid: "str" = None, check_storages: "bool" = True) -> "Instance": +def get_instance(id: str, metaid: str = None, check_storages: bool = True) -> "Instance": """Return instance with given id. Arguments: @@ -104,7 +104,6 @@ def get_instance(id: "str", metaid: "str" = None, check_storages: "bool" = True) Returns: DLite Instance. - """ if isinstance(id, Instance): inst = id diff --git a/bindings/python/dlite-entity.i b/bindings/python/dlite-entity.i index 7d69573a8..de6a1f35d 100644 --- a/bindings/python/dlite-entity.i +++ b/bindings/python/dlite-entity.i @@ -621,22 +621,21 @@ Call signatures: } %feature("docstring", "\ -Return property ``name`` as a string. +Return property `name` as a string. -Parameters: +Arguments: width: Minimum field width. Unused if 0, auto if -1. prec: Precision. Auto if -1, unused if -2. flags: Or'ed sum of formatting flags: - - ``0``: Default (json). - - ``1``: Raw unquoted output. - - ``2``: Quoted output. + - `0`: Default (json). + - `1`: Raw unquoted output. + - `2`: Quoted output. Returns: Property as a string. -") - get_property_as_string; +") get_property_as_string; %newobject get_property_as_string; char *get_property_as_string(const char *name, int width=0, int prec=-2, int flags=0) { diff --git a/bindings/python/dlite-misc-python.i b/bindings/python/dlite-misc-python.i index 738b688f0..b319c3bf2 100644 --- a/bindings/python/dlite-misc-python.i +++ b/bindings/python/dlite-misc-python.i @@ -8,12 +8,12 @@ class err(): """Context manager for temporary turning off or redirecting errors. By default errors are skipped within the err context. But if - ``filename`` is provided, the error messages are written to that file. + `filename` is provided, the error messages are written to that file. Special file names includes: - - ``None`` or empty: No output is written. - - ````: Write errors to stderr (default). - - ````: Write errors to stdout. + - "None" or empty: No output is written. + - "": Write errors to stderr (default). + - "": Write errors to stdout. """ def __init__(self, filename=None): diff --git a/bindings/python/dlite-misc.i b/bindings/python/dlite-misc.i index 25da852ea..89c3259aa 100644 --- a/bindings/python/dlite-misc.i +++ b/bindings/python/dlite-misc.i @@ -42,23 +42,23 @@ const char *dlite_get_license(void); %feature("docstring", "\ Returns an UUID, depending on: -- If ``id`` is NULL or empty, generates a new random version 4 UUID. -- If ``id`` is not a valid UUID string, generates a new version 5 sha1-based - UUID from ``id`` using the DNS namespace. +- If `id` is NULL or empty, generates a new random version 4 UUID. +- If `id` is not a valid UUID string, generates a new version 5 sha1-based + UUID from `id` using the DNS namespace. -Otherwise return ``id`` (which already must be a valid UUID). +Otherwise return `id` (which already must be a valid UUID). ") dlite_get_uuid; %cstring_bounded_output(char *buff36, DLITE_UUID_LENGTH+1); void dlite_get_uuid(char *buff36, const char *id=NULL); %feature("docstring", "\ -Returns the generated UUID version number if ``id`` had been passed to -get_uuid() or zero if ``id`` is already a valid UUID. +Returns the generated UUID version number if `id` had been passed to +get_uuid() or zero if `id` is already a valid UUID. ") get_uuid_version; posstatus_t get_uuid_version(const char *id=NULL); %feature("docstring", "\ -Returns a (metadata) uri by combining ``name``, ``version`` and ``namespace`` as: +Returns a (metadata) uri by combining `name`, `version` and `namespace` as: namespace/version/name ") dlite_join_meta_uri; @@ -68,7 +68,7 @@ char *dlite_join_meta_uri(const char *name, const char *version, %feature("docstring", "\ -Returns (name, version, namespace)-tuplet from valid metadata ``uri``. +Returns (name, version, namespace)-tuplet from valid metadata `uri`. ") dlite_split_meta_uri; %cstring_output_allocate(char **name, if (*$1) free(*$1)); %cstring_output_allocate(char **version, if (*$1) free(*$1)); @@ -83,7 +83,7 @@ Returns an url constructed from the arguments of the form: driver://location?options#fragment -The ``driver``, ``options`` and ``fragment`` arguments may be None. +The `driver`, `options` and `fragment` arguments may be None. ") dlite_join_url; %newobject dlite_join_url; char *dlite_join_url(const char *driver, const char *location, @@ -91,7 +91,7 @@ char *dlite_join_url(const char *driver, const char *location, %feature("docstring", "\ Returns a (driver, location, options, fragment)-tuplet by splitting -``url`` of the form +`url` of the form driver://location?options#fragment @@ -111,11 +111,11 @@ match. Understands the following patterns: -- ``*``: Any number of characters. -- ``?``: Any single character. -- ``[a-z]``: Any single character in the range a-z. -- ``[^a-z]``: Any single character not in the range a-z. -- ``\\x``: Match x. +- `*`: Any number of characters. +- `?`: Any single character. +- `[a-z]`: Any single character in the range a-z. +- `[^a-z]`: Any single character not in the range a-z. +- `\\x`: Match x. ") globmatch; int globmatch(const char *pattern, const char *s); @@ -150,9 +150,9 @@ void dlite_err_set_stream(FILE *); %feature("docstring", "\ Set error log file. Special values includes: -- ``None`` or empty: Turn off error output. -- ````: Standard error. -- ````: Standard output. +- `None` or empty: Turn off error output. +- ``: Standard error. +- ``: Standard output. All other values are treated as a filename that will be opened in append mode. ") dlite_err_set_file; diff --git a/bindings/python/dlite-python.i b/bindings/python/dlite-python.i index 7752c9897..a18ec276f 100644 --- a/bindings/python/dlite-python.i +++ b/bindings/python/dlite-python.i @@ -613,6 +613,7 @@ obj_t *dlite_swig_get_scalar(DLiteType type, size_t size, void *data) case 4: value = *((float32_t *)data); break; case 8: value = *((float64_t *)data); break; #ifdef HAVE_FLOAT80_T + // TODO: check for overflow case 10: value = *((float80_t *)data); break; #endif #ifdef HAVE_FLOAT96_T diff --git a/bindings/python/dlite-storage.i b/bindings/python/dlite-storage.i index 613938ca3..3a6c31c49 100644 --- a/bindings/python/dlite-storage.i +++ b/bindings/python/dlite-storage.i @@ -9,8 +9,8 @@ /* Storage iterator */ %feature("docstring", "\ -Iterates over instances in storage ``s``. If ``pattern`` is given, only -instances whos metadata URI matches ``pattern`` are returned. +Iterates over instances in storage `s`. If `pattern` is given, only +instances whos metadata URI matches `pattern` are returned. ") StorageIterator; %inline %{ struct StorageIterator { @@ -57,7 +57,7 @@ Returns next instance or None if exhausted.") next; enum _DLiteIDFlag { dliteIDTranslateToUUID=0, /*!< Translate id's that are not a valid UUID to a (version 5) UUID (default). */ - dliteIDRequireUUID=1, /*!< Require that ``id`` is a valid UUID. */ + dliteIDRequireUUID=1, /*!< Require that `id` is a valid UUID. */ dliteIDKeepID=2 /*!< Store data under the given id, even if it is not a valid UUID. Not SOFT compatible, but may be useful for input files. */ @@ -71,7 +71,7 @@ Represents a data storage. Parameters ---------- driver_or_url : string - Name of driver used to connect to the storage or, if ``location`` is not + Name of driver used to connect to the storage or, if `location` is not given, the URL to the storage: driver://location?options @@ -80,14 +80,8 @@ location : string The location to the storage. For file storages, this is the file name. options : string Additional options passed to the driver as a list of semicolon-separated - ``key=value`` pairs. Each driver may have their own options. Some - common options are: - - - ``mode={'append','r','w'}``: - - 'append': Append to existing storage or create a new one (hdf5,json). - - ``compact={'yes','no'}``: Whether to store in a compact format (json). - - ``meta={'yes','no'}``: Whether to format output as metadata (json). - + ``key=value`` pairs. See the documentation of the individual drivers to + see which options they support. ") _DLiteStorage; %rename(Storage) _DLiteStorage; @@ -138,7 +132,7 @@ struct _DLiteStorage { %feature("docstring", "Returns a list of UUIDs of all instances in the storage whos " - "metadata matches ``pattern``. If ``pattern`` is None, all UUIDs " + "metadata matches `pattern`. If `pattern` is None, all UUIDs " "will be returned.") get_uuids; char **get_uuids(const char *pattern=NULL) { return dlite_storage_uuids($self, pattern); diff --git a/bindings/python/factory.py b/bindings/python/factory.py index a791abf7d..7f0e5535e 100644 --- a/bindings/python/factory.py +++ b/bindings/python/factory.py @@ -1,10 +1,10 @@ # -*- coding: utf-8 -*- """A module that makes it easy to add dlite functionality to existing classes. -## Class customisations - -In order to handle special cases, the following methods may be defined/overridden in -the class that is to be extended: +Class customisations +-------------------- +In order to handle special cases, the following methods may be +defined/overridden in the class that is to be extended: ```python _dlite_get_(self, name) @@ -46,10 +46,11 @@ def __init__(cls, name, bases, attr) -> None: class BaseExtension(metaclass=MetaExtension): """Base class for extension. - Except for ``dlite_id``, all arguments are passed further to the ``__init__()`` - function of the class we are inheriting from. If ``instanceid`` is given, the id of - the underlying dlite instance will be set to it. + Except for `dlite_id`, all arguments are passed further to the `__init__()` + function of the class we are inheriting from. + If `instanceid` is given, the id of the underlying dlite instance + will be set to it. """ def __init__(self, *args, instanceid: str = None, **kwargs) -> None: @@ -59,11 +60,12 @@ def __init__(self, *args, instanceid: str = None, **kwargs) -> None: def _dlite_init(self, instanceid: str = None) -> None: """Initialise the underlying DLite Instance. - If ``id`` is given, the id of the underlying DLite Instance will be set to it. - - Parameters: - instanceid: A DLite ID (UUID) to use for the underlying DLite Instance. + If `id` is given, the id of the underlying DLite Instance will be + set to it. + Arguments: + instanceid: A DLite ID (UUID) to use for the underlying DLite + Instance. """ dims = self._dlite_infer_dimensions() self.dlite_inst = Instance.from_metaid( @@ -74,12 +76,11 @@ def _dlite_init(self, instanceid: str = None) -> None: def _dlite_get(self, name: str) -> "Any": """Returns the value of property `name` from the wrapped object. - Parameters: + Arguments: name: The property to retrieve. Returns: The property value. - """ if hasattr(self, f"_dlite_get_{name}"): return getattr(self, f"_dlite_get_{name}")() @@ -92,10 +93,9 @@ def _dlite_get(self, name: str) -> "Any": def _dlite_set(self, name: str, value: "Any") -> None: """Sets value of property ``name`` in the wrapped object. - Parameters: + Arguments: name: The property to set a value for. value: The value to set for the property. - """ if hasattr(self, f"_dlite_set_{name}"): getattr(self, f"_dlite_set_{name}")(value) @@ -154,9 +154,11 @@ def _dlite_assign_properties(self) -> None: def _dlite__new__(cls, inst=None): """Class method returning a new uninitialised instance of the class that is extended. - This method simply returns ``cls.__new__(cls)``. Override - this method if the extended class already defines a __new__() - method. + + This method simply returns `cls.__new__(cls)`. + + Override this method if the extended class already defines a + `__new__()` method. """ return cls.__new__(cls) @@ -179,15 +181,16 @@ def dlite_load(self, *args) -> None: def instancefactory(theclass: type, inst: Instance) -> "Any": - """Returns an extended instance of ``theclass`` initiated from dlite + """Returns an extended instance of `theclass` initiated from dlite instance ``inst``. - Parameters: - theclass: The class to instantiate an object from using ``inst``. - inst: A DLite Instance to use as source for a ``theclass`` instance object. + Arguments: + theclass: The class to instantiate an object from using `inst`. + inst: A DLite Instance to use as source for a `theclass` instance + object. Returns: - A ``theclass`` instance object based on the DLite Instance ``inst``. + A `theclass` instance object based on the DLite Instance `inst`. """ cls = classfactory(theclass, meta=inst.meta) @@ -208,30 +211,26 @@ def objectfactory( id: "Optional[str]" = None, instanceid: "Optional[str]" = None, ) -> "Any": - """Returns an extended copy of ``obj``. - - If ``deepcopy`` is ``True``, a deep copy is returned, otherwise a shallow copy is - returned. By default, the returned object will have the same class as ``obj``. - If ``cls`` is provided, the class of the returned object will be set to ``cls`` - (typically a subclass of ``obj.__class__``). + """Returns an extended copy of `obj`. - The ``url``, ``storage``, and ``id`` arguments are passed to ``classfactory()``. + The `url`, `storage`, and `id` arguments are passed to `classfactory()`. - Parameters: + Arguments: obj: A Python object. meta: A DLite Metadata Instance. - deepcopy: Whether or not to perform a deep or shallow copy of ``obj``. - cls: A class to use for the new object. If this is not supplied, the new object - will be the same class as the original. - url: URL referring to the metadata. Should be of the form - ``driver://location?options#id``. Only used if ``cls`` is not specified. - storage: Storage from which to load meta data. Only used if ``cls`` is not - specified. - id: A unique ID referring to the meta data if ``storage`` is provided. + deepcopy: Whether to perform a deep copy. Otherwise a shallow copy + is performed. + cls: A class to use for the new object. If this is not supplied, + the new object will be of the same class as the original. + url: If given and `meta` is not given, load metadata from this URL. + It should be of the form `driver://location?options#id`. + storage: If given and `meta` and `url` are not given, load metadata + from this storage. + id: A unique ID referring to the metadata if `storage` is provided. instanceid: A DLite ID (UUID) to use for the underlying DLite Instance. Returns: - A new, extended copy of the Python object ``obj``. + A new, extended copy of the Python object `obj`. """ cls = cls if cls is not None else classfactory( @@ -255,18 +254,19 @@ def classfactory( id: "Optional[str]" = None, ) -> type: """Factory function that returns a new class that inherits from both - ``theclass`` and ``BaseExtension``. + `theclass` and `BaseExtension`. - Parameters: + Arguments: theclass: The class to extend. meta: Metadata instance. - url: URL referring to the metadata. Should be of the form - ``driver://location?options#id``. - storage: Storage to load meta from. - id: A unique ID referring to the metadata if ``storage`` is provided. + url: If given and `meta` is not given, load metadata from this URL. + It should be of the form `driver://location?options#id`. + storage: If given and `meta` and `url` are not given, load metadata + from this storage. + id: A unique ID referring to the metadata if `storage` is provided. Returns: - A new class based on ``theclass`` and ``BaseExtensions``. + A new class based on `theclass` and `BaseExtensions`. """ if meta is None: diff --git a/bindings/python/mappings.py b/bindings/python/mappings.py index bce69dd86..529518111 100644 --- a/bindings/python/mappings.py +++ b/bindings/python/mappings.py @@ -74,7 +74,6 @@ class Value: property_iri: IRI of datamodel property that this value is an instance of. cost: Cost of accessing this value. - """ def __init__( self, @@ -106,17 +105,16 @@ def show( Returns: String representation of the value. - """ - res = [] ind = " " * indent - res.append(ind + f"{name if name else 'Value'}:") - res.append(ind + f" iri: {self.iri}") - res.append(ind + f" property_iri: {self.property_iri}") - res.append(ind + f" unit: {self.unit}") - res.append(ind + f" cost: {self.cost}") - res.append(ind + f" value: {self.value}") - return "\n".join(res) + result = [] + result.append(ind + f"{name if name else 'Value'}:") + result.append(ind + f" iri: {self.iri}") + result.append(ind + f" property_iri: {self.property_iri}") + result.append(ind + f" unit: {self.unit}") + result.append(ind + f" cost: {self.cost}") + result.append(ind + f" value: {self.value}") + return "\n".join(result) class MappingStep: @@ -132,7 +130,7 @@ class MappingStep: steptype: One of the step types from the StepType enum. function: Callable that evaluates the output from the input. cost: The cost related to this mapping step. Should be either a - float or a callable taking the same arguments as ``function`` as + float or a callable taking the same arguments as `function` as input returning the cost as a float. output_unit: Output unit. @@ -164,14 +162,14 @@ def add_inputs(self, inputs: dict) -> None: def add_input( self, input: "MappingStep | Value", name: "Optional[str]" = None ) -> None: - """Add an input (MappingStep or Value), where ``name`` is the name + """Add an input (MappingStep or Value), where `name` is the name assigned to the argument. - If the ``join_mode`` attribute is ``False``, a new route is created with + If the `join_mode` attribute is `False`, a new route is created with only one input. - If the ``join_mode`` attribute is ``True``, the input is remembered, but - first added when ``join_input()`` is called. + If the `join_mode` attribute is `True`, the input is remembered, but + first added when `join_input()` is called. Arguments: input: A mapping step or a value. @@ -206,7 +204,7 @@ def eval( """Returns the evaluated value of given input route number. Arguments: - routeno: The route number to evaluate. If ``None`` (default) + routeno: The route number to evaluate. If `None` (default) the route with the lowest cost is evalueated. unit: return the result in the given unit. Implies `magnitude=True`. magnitude: Whether to only return the magnitude of the evaluated @@ -238,7 +236,7 @@ def eval( def get_inputs(self, routeno: int) -> tuple[dict, int]: """Returns input and input index ``(inputs, idx)`` for route number - ``routeno``. + `routeno`. Arguments: routeno: The route number to return inputs for. @@ -286,8 +284,8 @@ def number_of_routes(self) -> int: return n def lowest_costs(self, nresults: int = 5) -> list: - """Returns a list of ``(cost, routeno)`` tuples with up to the ``nresults`` - lowest costs and their corresponding route numbers. + """Returns a list of ``(cost, routeno)`` tuples with up to the + `nresults` lowest costs and their corresponding route numbers. Arguments: nresults: Number of results to return. @@ -413,7 +411,7 @@ def get_nroutes(inputs: "dict[str, Any]") -> int: inputs: Input dictionary. Returns: - Number of routes in the ``inputs`` input dictionary. + Number of routes in the `inputs` input dictionary. """ nroutes = 1 @@ -432,8 +430,8 @@ def get_values( """Help function returning a dict mapping the input names to actual value of expected input unit. - There exists ``get_nroutes(inputs)`` routes to populate ``inputs``. - ``routeno`` is the index of the specific route we will use to obtain the + There exists ``get_nroutes(inputs)`` routes to populate `inputs`. + `routeno` is the index of the specific route we will use to obtain the values. Arguments: @@ -479,7 +477,10 @@ def fno_mapper(triplestore: "Triplestore") -> defaultdict: triplestore: The triplestore to investigate. Returns: - A mapping of output IRIs to a list of ``(function_iri, [input_iris, ...])`` + A mapping of output IRIs to a list of + + (function_iri, [input_iris, ...]) + tuples. """ @@ -1095,8 +1096,8 @@ def make_instance( props[prop.name] = value elif props[prop.name] != value: raise AmbiguousMappingError( - f"{prop.name!r} maps to both " - f"{props[prop.name]!r} and {value!r}" + f"'{prop.name}' maps to both " + f"'{props[prop.name]}' and '{value}'" ) if prop.name not in props and not strict: @@ -1108,20 +1109,20 @@ def make_instance( props[prop.name] = value elif props[prop.name] != value: raise AmbiguousMappingError( - f"{prop.name!r} assigned to both " - f"{props[prop.name]!r} and {value!r}" + f"'{prop.name}' assigned to both " + f"'{props[prop.name]}' and '{value}'" ) if not allow_incomplete and prop.name not in props: raise InsufficientMappingError( - f"no mapping for assigning property {prop.name!r} " + f"no mapping for assigning property '{prop.name}' " f"in {meta.uri}" ) if None in dims: dimname = [name for name, dim in dims.items() if dim is None][0] raise InsufficientMappingError( - f"dimension {dimname!r} is not assigned" + f"dimension '{dimname}' is not assigned" ) inst = meta(list(dims.values()))