diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index 5565051d0..2792e48a9 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -2,7 +2,7 @@ ## Type of change -- [ ] Bug fix +- [ ] Bug fix & code cleanup - [ ] New feature - [ ] Documentation update - [ ] Test update diff --git a/bindings/python/dlite-entity-python.i b/bindings/python/dlite-entity-python.i index 1bca7aa96..8cae90479 100644 --- a/bindings/python/dlite-entity-python.i +++ b/bindings/python/dlite-entity-python.i @@ -93,7 +93,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: @@ -105,7 +105,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 76c83980c..3add8b3e4 100644 --- a/bindings/python/dlite-entity.i +++ b/bindings/python/dlite-entity.i @@ -622,22 +622,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 0e94a873d..cb622eeeb 100644 --- a/bindings/python/dlite-python.i +++ b/bindings/python/dlite-python.i @@ -592,6 +592,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())) diff --git a/bindings/python/tests/test_storage.py b/bindings/python/tests/test_storage.py index 103206659..4b7c14212 100755 --- a/bindings/python/tests/test_storage.py +++ b/bindings/python/tests/test_storage.py @@ -59,10 +59,10 @@ expected = """\ DLite storage plugin for YAML. -Opens `uri`. +Opens `location`. Arguments: - uri: A fully resolved URI to the PostgreSQL database. + location: Path to YAML file. options: Supported options: - `mode`: Mode for opening. Valid values are: - `a`: Append to existing file or create new file (default). @@ -70,7 +70,7 @@ - `w`: Truncate existing file or create new file. - `soft7`: Whether to save using SOFT7 format. - `single`: Whether the input is assumed to be in single-entity form. - The default (`"auto"`) will try to infer it automatically. + If "auto" (default) the form will be inferred automatically. """ s = dlite.Storage('yaml', 'inst.yaml', options='mode=a') assert s.help().strip() == expected.strip() diff --git a/doc/getting_started/tutorial.md b/doc/getting_started/tutorial.md index bd6726fa3..c1a9f2bed 100644 --- a/doc/getting_started/tutorial.md +++ b/doc/getting_started/tutorial.md @@ -79,98 +79,92 @@ We will give our dimension the generic name "N", and describe it as the number o ```json "uri": "http://www.ontotrans.eu/0.1/solarPanelMeasurement", "meta": "http://onto-ns.com/meta/0.3/EntitySchema", -"description": - "dimensions": [ - { - "name": "N", - "description": "Number of measurements." - } - ] +"description": "Measurement data from one solar panel.", +"dimensions": { + "N": "Number of measurements." +} ``` ### **Step 5**: Defining the properties -Now it is time to define the properties of our Entity. Here is where we can give meaning to our data. As for the dimensions, we add the properties as a list of `json` structures, each one having a **name**, **type**, **description**, and if relevant, **unit** and **shape** (the dimensionality of the property). Inserting the properties displayed in the table above, our Entity is complete and may look like +Now it is time to define the properties of our Entity. +Here is where we can give meaning to our data. +As for the dimensions, we add the properties as a list of `json` structures, each one having a **name**, **type**, **description**, and if relevant, **unit**, **shape** (the dimensionality of the property) and **ref** (the metadata for *ref* types). + +Inserting the properties displayed in the table above, our Entity is complete and may look like ```json { "uri": "http://www.ontotrans.eu/0.1/solarPanelMeasurement", "meta": "http://onto-ns.com/meta/0.3/EntitySchema", "description": "Measurement data from one solar panel.", - "dimensions": [ - { - "name": "N", - "description": "Number of measurements." - } - ], - "properties": [ - { - "name":"t", + "dimensions": { + "N": "Number of measurements." + }, + "properties": { + "t": { "type":"str", "unit":"ns", "shape": ["N"], "description": "Time" }, - { - "name":"MPP", + "MPP": { "type":"float64", "unit":"W", "shape": ["N"], "description": "Maximum Power" }, - { - "name": "impp", + "impp": { "type": "float64", "unit": "A", "shape": ["N"], "description": "Maximum power point current." }, - { - "name": "isc", + "isc": { "type": "float64", "unit": "A", "shape": ["N"], "description": "Short circuit current." }, - { - "name": "vmpp", + "vmpp": { "type": "float64", "unit": "V", "shape": ["N"], "description": "Maximum power point voltage." }, - { - "name": "voc", + "voc": { "type": "float64", "unit": "V", "shape": ["N"], "description": "Open circuit voltage." } - ] + } } ``` :::{note} -Both dimensions and properties can also be provided using a `dict` with the name as key. This may look like +Both dimensions and properties can also be provided as arrays using a `dict` with the name as key. This may look like ```json - "dimensions": { - "N": "Number of measurements." - }, - "properties": { - "t": { + "dimensions": [ + {"name": "N", "description": "Number of measurements."} + ] + "properties": [ + { + "name": "t", "type":"str", "unit":"ns", "shape": ["N"], "description": "Time" }, - "MPP": { + { + "name": "MPP", "type":"float64", "unit":"W", "shape": ["N"], "description": "Maximum Power" }, - ... - } + ... + ] ``` DLite supports both syntaxes. ::: diff --git a/src/pyembed/dlite-python-singletons.c b/src/pyembed/dlite-python-singletons.c index 696664a55..eb7233047 100644 --- a/src/pyembed/dlite-python-singletons.c +++ b/src/pyembed/dlite-python-singletons.c @@ -208,7 +208,7 @@ PyObject *dlite_python_module_error(DLiteErrors code) /* Create exception */ count = snprintf(excname, sizeof(excname), "dlite.%s", errname); - assert(count > 0 && count < sizeof(excname)); + assert(count > 0 && count < (int)sizeof(excname)); errdescr = dlite_errdescr(code); if (!(exc = PyErr_NewExceptionWithDoc(excname, errdescr, base, NULL))) diff --git a/storages/python/python-storage-plugins/blob.json b/storages/python/python-storage-plugins/blob.json index 682c96452..2e0b874af 100644 --- a/storages/python/python-storage-plugins/blob.json +++ b/storages/python/python-storage-plugins/blob.json @@ -1,21 +1,15 @@ { - "name": "Blob", - "version": "0.1", - "namespace": "http://onto-ns.com/meta", + "uri": "http://onto-ns.com/meta/0.1/Blob", "description": "Entity representing a single binary blob as a sequence of bytes.", - "dimensions": [ - { - "name": "n", - "description": "Size of blob(i.e. number of bytes)." - } - ], - "properties": [ - { - "name": "content", + "dimensions": { + "n": "Size of blob (i.e. number of bytes)." + }, + "properties": { + "content": { "type": "uint8", - "dims": ["n"], + "shape": ["n"], "unit": "bytes", "description": "Content of the binary blob." } - ] + } } diff --git a/storages/python/python-storage-plugins/yaml.py b/storages/python/python-storage-plugins/yaml.py index b8f2c9322..56dfabdf4 100644 --- a/storages/python/python-storage-plugins/yaml.py +++ b/storages/python/python-storage-plugins/yaml.py @@ -1,4 +1,4 @@ -"""A simple demonstrage of a DLite storage plugin written in Python.""" +"""DLite YAML storage plugin written in Python.""" import os from typing import TYPE_CHECKING @@ -16,11 +16,11 @@ class yaml(dlite.DLiteStorageBase): """DLite storage plugin for YAML.""" _pyyaml = pyyaml # Keep a reference to pyyaml to have it during shutdown - def open(self, uri: str, options=None): - """Opens `uri`. + def open(self, location: str, options=None): + """Opens `location`. Arguments: - uri: A fully resolved URI to the PostgreSQL database. + location: Path to YAML file. options: Supported options: - `mode`: Mode for opening. Valid values are: - `a`: Append to existing file or create new file (default). @@ -28,7 +28,7 @@ def open(self, uri: str, options=None): - `w`: Truncate existing file or create new file. - `soft7`: Whether to save using SOFT7 format. - `single`: Whether the input is assumed to be in single-entity form. - The default (`"auto"`) will try to infer it automatically. + If "auto" (default) the form will be inferred automatically. """ self.options = Options( options, defaults="mode=a;soft7=true;single=auto" @@ -36,11 +36,11 @@ def open(self, uri: str, options=None): self.readable = "r" in self.options.mode self.writable = "r" != self.options.mode self.generic = True - self.uri = uri + self.location = location self.flushed = False # whether buffered data has been written to file self._data = {} # data buffer if self.options.mode in ("r", "a", "append"): - with open(uri, "r") as f: + with open(location, "r") as f: data = pyyaml.safe_load(f) if data: self._data = data @@ -53,7 +53,7 @@ def open(self, uri: str, options=None): def flush(self): """Flush cached data to storage.""" if self.writable and not self.flushed: - with open(self.uri, "w") as f: + with open(self.location, "w") as f: self._pyyaml.safe_dump( self._data, f,