Commit 713a0961 authored by Samuel GAIST's avatar Samuel GAIST
Browse files

[dataformat] Pre-commit cleanup

parent 71d8ad07
......@@ -70,21 +70,20 @@ class Storage(utils.Storage):
def __init__(self, prefix, name):
if name.count('/') != 2:
if name.count("/") != 2:
raise RuntimeError("invalid dataformat name: `%s'" % name)
self.username,, self.version = name.split('/')
self.username,, self.version = name.split("/")
self.fullname = name
self.prefix = prefix
path = utils.hashed_or_simple(self.prefix, 'dataformats', name, suffix='.json')
path = utils.hashed_or_simple(self.prefix, "dataformats", name, suffix=".json")
path = path[:-5]
super(Storage, self).__init__(path)
def hash(self):
"""The 64-character hash of the database declaration JSON"""
return super(Storage, self).hash('#description')
return super(Storage, self).hash("#description")
# ----------------------------------------------------------
......@@ -165,23 +164,24 @@ class DataFormat(object):
if self._name is not None: # registers it into the cache, even if failed
dataformat_cache[self._name] = self
def _load(self, data, dataformat_cache):
"""Loads the dataformat"""
if isinstance(data, dict):
self._name = 'analysis:result'
self._name = "analysis:result" = data
self._name = data = Storage(self.prefix, data)
json_path =
if not
self.errors.append('Dataformat declaration file not found: %s' % json_path)
"Dataformat declaration file not found: %s" % json_path
with open(json_path, 'rb') as f: = simplejson.loads('utf-8'))
with open(json_path, "rb") as f: = simplejson.loads("utf-8"))
dataformat_cache[self._name] = self # registers itself into the cache
......@@ -189,17 +189,20 @@ class DataFormat(object):
# remove reserved fields
def is_reserved(x):
'''Returns if the field name is a reserved name'''
return (x.startswith('__') and x.endswith('__')) or \
x in ('#description', '#schema_version')
"""Returns if the field name is a reserved name"""
return (x.startswith("__") and x.endswith("__")) or x in (
for key in list(self.resolved):
if is_reserved(key): del self.resolved[key]
if is_reserved(key):
del self.resolved[key]
def maybe_load_format(name, obj, dataformat_cache):
"""Tries to load a given dataformat from its relative path"""
if isinstance(obj, six.string_types) and obj.find('/') != -1: # load it
if isinstance(obj, six.string_types) and obj.find("/") != -1: # load it
if obj in dataformat_cache: # reuse
......@@ -209,8 +212,9 @@ class DataFormat(object):
self.referenced[obj] = dataformat_cache[obj]
else: # load it
self.referenced[obj] = DataFormat(self.prefix, obj, (self, name),
self.referenced[obj] = DataFormat(
self.prefix, obj, (self, name), dataformat_cache
return self.referenced[obj]
......@@ -226,22 +230,22 @@ class DataFormat(object):
# now checks that every referred dataformat is loaded, resolves it
for field, value in
if field in ('#description', '#schema_version'):
if field in ("#description", "#schema_version"):
continue # skip the description and schema version meta attributes
self.resolved[field] = maybe_load_format(field, value, dataformat_cache)
# at this point, there should be no more external references in
# ``self.resolved``. We treat the "#extends" property, which requires a
# special handling, given its nature.
if '#extends' in self.resolved:
if "#extends" in self.resolved:
ext =['#extends']
ext =["#extends"]
self.referenced[ext] = maybe_load_format(self._name, ext, dataformat_cache)
basetype = self.resolved['#extends']
basetype = self.resolved["#extends"]
tmp = self.resolved
self.resolved = basetype.resolved
del self.resolved['#extends'] # avoids infinite recursion
del self.resolved["#extends"] # avoids infinite recursion
def name(self):
......@@ -249,29 +253,25 @@ class DataFormat(object):
from the hierarchy it belongs.
if self.parent and self._name is None:
return self.parent[0].name + '.' + self.parent[1] + '_type'
return self.parent[0].name + "." + self.parent[1] + "_type"
return self._name or '__unnamed_dataformat__'
return self._name or "__unnamed_dataformat__"
def name(self, value):
self._name = value = Storage(self.prefix, value)
def schema_version(self):
"""Returns the schema version"""
return'#schema_version', 1)
return"#schema_version", 1)
def extends(self):
"""If this dataformat extends another one, this is it, otherwise ``None``
def type(self):
......@@ -305,16 +305,14 @@ class DataFormat(object):
if self.resolved is None:
raise RuntimeError("Cannot prototype while not properly initialized")
classname = re.sub(r'[-/]', '_',
if not isinstance(classname, str): classname = str(classname)
classname = re.sub(r"[-/]", "_",
if not isinstance(classname, str):
classname = str(classname)
def init(self, **kwargs): baseformat.__init__(self, **kwargs)
def init(self, **kwargs):
baseformat.__init__(self, **kwargs)
attributes = dict(
attributes = dict(__init__=init,, _format=self.resolved)
# create the converters for the class we're about to return
for k, v in self.resolved.items():
......@@ -324,7 +322,7 @@ class DataFormat(object):
if isinstance(v[-1], DataFormat):
attributes[k][-1] = v[-1].type
if v[-1] in ('string', 'str'):
if v[-1] in ("string", "str"):
attributes[k][-1] = str
attributes[k][-1] = numpy.dtype(v[-1])
......@@ -333,35 +331,27 @@ class DataFormat(object):
attributes[k] = v.type
else: # it is a simple type
if v in ('string', 'str'):
if v in ("string", "str"):
attributes[k] = str
attributes[k] = numpy.dtype(v)
return type(
return type(classname, (baseformat,), attributes)
def valid(self):
"""A boolean that indicates if this dataformat is valid or not"""
return not bool(self.errors)
def description(self):
"""The short description for this object"""
return'#description', None)
return"#description", None)
def description(self, value):
"""Sets the short description for this object"""['#description'] = value["#description"] = value
def documentation(self):
......@@ -374,7 +364,6 @@ class DataFormat(object):
return None
def documentation(self, value):
"""Sets the full-length description for this object"""
......@@ -382,12 +371,11 @@ class DataFormat(object):
if not self._name:
raise RuntimeError("dataformat has no name")
if hasattr(value, 'read'):
if hasattr(value, "read"):
def hash(self):
"""Returns the hexadecimal hash for its declaration"""
......@@ -396,7 +384,6 @@ class DataFormat(object):
def validate(self, data):
"""Validates a piece of data provided by the user
......@@ -421,13 +408,12 @@ class DataFormat(object):
obj = self.type()
if isinstance(data, dict):
obj.from_dict(data, casting='safe', add_defaults=False)
obj.from_dict(data, casting="safe", add_defaults=False)
elif isinstance(data, six.string_types):
def isparent(self, other):
"""Tells if the other object extends self (directly or indirectly).
......@@ -451,7 +437,6 @@ class DataFormat(object):
return False
def json_dumps(self, indent=4):
"""Dumps the JSON declaration of this object in a string
......@@ -467,14 +452,11 @@ class DataFormat(object):
return simplejson.dumps(, indent=indent,
return simplejson.dumps(, indent=indent, cls=utils.NumpyJSONEncoder)
def __str__(self):
return self.json_dumps()
def write(self, storage=None):
"""Writes contents to prefix location
......@@ -493,7 +475,6 @@ class DataFormat(object):, self.description)
def export(self, prefix):
"""Recursively exports itself into another prefix
......@@ -523,8 +504,9 @@ class DataFormat(object):
raise RuntimeError("dataformat is not valid")
if prefix == self.prefix:
raise RuntimeError("Cannot export dataformat to the same prefix ("
"%s)" % prefix)
raise RuntimeError(
"Cannot export dataformat to the same prefix (" "%s)" % prefix
for k in self.referenced.values():
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment