Skip to content

Commit

Permalink
Code cleanup (#591)
Browse files Browse the repository at this point in the history
# Description
Reverting some bad code and formatting that was unfortunately
introduced.

## Type of change
- [x] Bug fix
- [ ] New feature
- [ ] Documentation update
- [ ] Test update

## Checklist for the reviewer
This checklist should be used as a help for the reviewer.

- [ ] Is the change limited to one issue?
- [ ] Does this PR close the issue?
- [ ] Is the code easy to read and understand?
- [ ] Do all new feature have an accompanying new test?
- [ ] Has the documentation been updated as necessary?
  • Loading branch information
jesper-friis authored Aug 13, 2023
2 parents e95df2c + 3e55b79 commit 944f778
Show file tree
Hide file tree
Showing 8 changed files with 114 additions and 120 deletions.
3 changes: 1 addition & 2 deletions bindings/python/dlite-entity-python.i
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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
Expand Down
13 changes: 6 additions & 7 deletions bindings/python/dlite-entity.i
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
8 changes: 4 additions & 4 deletions bindings/python/dlite-misc-python.i
Original file line number Diff line number Diff line change
Expand Up @@ -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.
- ``<stderr>``: Write errors to stderr (default).
- ``<stdout>``: Write errors to stdout.
- "None" or empty: No output is written.
- "<stderr>": Write errors to stderr (default).
- "<stdout>": Write errors to stdout.
"""
def __init__(self, filename=None):
Expand Down
36 changes: 18 additions & 18 deletions bindings/python/dlite-misc.i
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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));
Expand All @@ -83,15 +83,15 @@ 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,
const char *options=NULL, const char *fragment=NULL);

%feature("docstring", "\
Returns a (driver, location, options, fragment)-tuplet by splitting
``url`` of the form
`url` of the form
driver://location?options#fragment
Expand All @@ -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);

Expand Down Expand Up @@ -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.
- ``<stderr>``: Standard error.
- ``<stdout>``: Standard output.
- `None` or empty: Turn off error output.
- `<stderr>`: Standard error.
- `<stdout>`: Standard output.

All other values are treated as a filename that will be opened in append mode.
") dlite_err_set_file;
Expand Down
1 change: 1 addition & 0 deletions bindings/python/dlite-python.i
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
20 changes: 7 additions & 13 deletions bindings/python/dlite-storage.i
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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. */
Expand All @@ -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
Expand All @@ -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;

Expand Down Expand Up @@ -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);
Expand Down
94 changes: 47 additions & 47 deletions bindings/python/factory.py
Original file line number Diff line number Diff line change
@@ -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_<name>(self, name)
Expand Down Expand Up @@ -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:
Expand All @@ -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(
Expand All @@ -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}")()
Expand All @@ -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)
Expand Down Expand Up @@ -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)

Expand All @@ -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)
Expand All @@ -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(
Expand All @@ -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:
Expand Down
Loading

0 comments on commit 944f778

Please sign in to comment.