Skip to content

Commit

Permalink
Merge branch 'master' into entity-formatting
Browse files Browse the repository at this point in the history
  • Loading branch information
jesper-friis authored Aug 13, 2023
2 parents f642482 + 944f778 commit b618caf
Show file tree
Hide file tree
Showing 25 changed files with 725 additions and 266 deletions.
8 changes: 4 additions & 4 deletions bindings/python/dlite-collection-python.i
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@ class Collection(Instance):
def remove(self, label):
"""Remove instance with given label from collection."""
if _collection_remove(self._coll, label):
raise DLiteError(f'No such label in collection: "{label}"')
raise _dlite.DLiteError(f'No such label in collection: "{label}"')

def get(self, label, metaid=None):
"""Return instance with given label.
Expand Down Expand Up @@ -189,12 +189,12 @@ class Collection(Instance):
def add_relation(self, s, p, o):
"""Add (subject, predicate, object) RDF triple to collection."""
if _collection_add_relation(self._coll, s, p, o) != 0:
raise DLiteError(f'Error adding relation ({s}, {p}, {o})')
raise _dlite.DLiteError(f'Error adding relation ({s}, {p}, {o})')

def remove_relations(self, s=None, p=None, o=None):
"""Remove all relations matching `s`, `p` and `o`."""
if _collection_remove_relations(self._coll, s, p, o) < 0:
raise DLiteError(
raise _dlite.DLiteError(
f'Error removing relations matching ({s}, {p}, {o})')

def get_first_relation(self, s=None, p=None, o=None):
Expand Down Expand Up @@ -280,7 +280,7 @@ class Collection(Instance):
):
yield inst
elif property_mappings:
raise DLiteError(
raise _dlite.DLiteError(
'`metaid` is required when `property_mappings` is true')
else:
for inst in iter:
Expand Down
19 changes: 10 additions & 9 deletions bindings/python/dlite-entity-python.i
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,8 @@ class Metadata(Instance):
lst = [p for p in self.properties["properties"] if p.name == name]
if lst:
return lst[0]
raise DLiteError(f"Metadata {self.uri} has no such property: {name}")
raise _dlite.DLiteError(
f"Metadata {self.uri} has no such property: {name}")
def dimnames(self):
"""Returns a list of all dimension names in this metadata."""
Expand Down Expand Up @@ -92,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 @@ -104,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 All @@ -115,7 +115,7 @@ def get_instance(id: "str", metaid: "str" = None, check_storages: "bool" = True)
inst = _dlite.get_instance(id, metaid, check_storages)

if inst is None:
raise DLiteError(f"no such instance: {id}")
raise _dlite.DLiteError(f"no such instance: {id}")
elif inst.is_meta:
inst.__class__ = Metadata
elif inst.meta.uri == COLLECTION_ENTITY:
Expand Down Expand Up @@ -267,13 +267,13 @@ def get_instance(id: "str", metaid: "str" = None, check_storages: "bool" = True)
# Override default generated __init__() method
def __init__(self, *args, **kwargs):
if self is None:
raise DLiteError(f"invalid dlite.Instance")
raise _dlite.DLiteError(f"invalid dlite.Instance")
_dlite.errclr()
_dlite.Instance_swiginit(self, _dlite.new_Instance(*args, **kwargs))
if not hasattr(self, 'this') or not getattr(self, 'this'):
raise DLiteError(f"cannot initiate dlite.Instance")
raise _dlite.DLiteError(f"cannot initiate dlite.Instance")
elif self.is_meta:
self.__class__ = Metadata
elif self.meta.uri == COLLECTION_ENTITY:
Expand Down Expand Up @@ -487,7 +487,7 @@ def get_instance(id: "str", metaid: "str" = None, check_storages: "bool" = True)
elif isinstance(dest, str):
self.save_to_url(dest)
else:
raise DLiteError('Arguments do not match any call signature')
raise _dlite.DLiteError('Arguments do not match any call signature')

def __getitem__(self, ind):
if isinstance(ind, int):
Expand All @@ -504,7 +504,8 @@ def get_instance(id: "str", metaid: "str" = None, check_storages: "bool" = True)

def __setitem__(self, ind, value):
if self.is_frozen():
raise DLiteError('frozen instance does not support item assignment')
raise _dlite.DLiteError(
'frozen instance does not support item assignment')
if isinstance(ind, int):
self.set_property_by_index(ind, value)
elif self.has_property(ind):
Expand Down Expand Up @@ -537,7 +538,7 @@ def get_instance(id: "str", metaid: "str" = None, check_storages: "bool" = True)
if name == 'this':
object.__setattr__(self, name, value)
elif self.is_frozen():
raise DLiteError(
raise _dlite.DLiteError(
'frozen instance does not support attribute assignment')
elif _has_property(self, name):
_set_property(self, name, value)
Expand Down
22 changes: 13 additions & 9 deletions bindings/python/dlite-entity.i
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
%{
#include "dlite-mapping.h"
#include "dlite-bson.h"
#include "dlite-errors.h"
%}


Expand Down Expand Up @@ -410,7 +411,11 @@ Call signatures:
void to_bytes(const char *driver, unsigned char **ARGOUT_BYTES, size_t *LEN) {
unsigned char *buf=NULL;
int m, n = dlite_instance_memsave(driver, buf, 0, $self);
if (n < 0) return;
if (n < 0) {
*ARGOUT_BYTES = NULL;
*LEN = 0;
return;
}
if (!(buf = malloc(n))) {
dlite_err(dliteMemoryError, "allocation failure");
return;
Expand Down Expand Up @@ -465,7 +470,7 @@ Call signatures:
hashp = data;
}
if (dlite_instance_verify_hash($self, hashp, recursive))
dlite_swig_exception = DLiteVerifyError;
dlite_swig_exception = dlite_python_module_error(dliteVerifyError);
}

%feature("docstring",
Expand Down Expand Up @@ -617,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
36 changes: 10 additions & 26 deletions bindings/python/dlite-python.i
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,6 @@
PyObject *dlite_swig_exception = NULL;

/* forward declarations */
static PyObject *DLiteError = NULL;
static PyObject *DLiteVerifyError = NULL;
char *strndup(const char *s, size_t n);
%}

Expand Down Expand Up @@ -62,21 +60,7 @@ int dlite_swig_set_scalar(void *ptr, DLiteType type, size_t size, obj_t *obj);

%init %{
Py_Initialize(); /* should already be called, but just in case... */
import_array(); /* Initialize numpy */

DLiteError = PyErr_NewExceptionWithDoc(
"dlite.DLiteError", // name
"Base exception for the dlite module.", // doc
NULL, // base
NULL // dict
);

DLiteVerifyError = PyErr_NewExceptionWithDoc(
"dlite.DLiteVerifyError", // name
"Object cannot be verified.", // doc
DLiteError, // base
NULL // dict
);
import_array(); /* Initialize numpy */
%}

%numpy_typemaps(unsigned char, NPY_UBYTE, size_t)
Expand All @@ -92,11 +76,8 @@ int dlite_swig_set_scalar(void *ptr, DLiteType type, size_t size, obj_t *obj);
**********************************************/
%{

PyObject *_get_DLiteError(void) {
return DLiteError;
}
PyObject *_get_DLiteVerifyError(void) {
return DLiteVerifyError;
int _get_number_of_errors(void) {
return -dliteLastError;
}

/* Free's array of allocated strings. */
Expand Down Expand Up @@ -611,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 Expand Up @@ -1380,12 +1362,14 @@ PyObject *dlite_python_mapping_base(void);
/* ------------------
* Expose generic api
* ------------------ */
PyObject *_get_DLiteError(void);
PyObject *_get_DLiteVerifyError(void);
%rename(_get_dlite_error) dlite_python_module_error;
PyObject *dlite_python_module_error(int code);
int _get_number_of_errors(void);

%pythoncode %{
DLiteError = _dlite._get_DLiteError()
DLiteVerifyError = _dlite._get_DLiteVerifyError()
for n in range(_dlite._get_number_of_errors()):
exc = _get_dlite_error(-n)
setattr(_dlite, exc.__name__, exc)
DLiteStorageBase = _dlite._get_storage_base()
DLiteMappingBase = _dlite._get_mapping_base()
%}
Loading

0 comments on commit b618caf

Please sign in to comment.