[PATCH 24 of 24 yams V2] [style] remove useless exception

Nicola Spanti nicola.spanti at logilab.fr
Wed Mar 4 16:48:28 CET 2020


Le 04/03/2020 à 15:18, Laurent Peuch a écrit :
> # HG changeset patch
> # User Laurent Peuch <cortex at worlddomination.be>
> # Date 1582763700 -3600
> #      Thu Feb 27 01:35:00 2020 +0100
> # Node ID 843671e4e6c36004510654433c83751ad525f7db
> # Parent  c52784b56910b156b78bfda6922938fd6b5850b1
> # Available At https://hg.logilab.org/users/lpeuch/yams
> #              hg pull https://hg.logilab.org/users/lpeuch/yams -r 843671e4e6c3
> # EXP-Topic type_annotations
> [style] remove useless exception
> 
> diff --git a/yams/__init__.py b/yams/__init__.py
> --- a/yams/__init__.py
> +++ b/yams/__init__.py
> @@ -103,13 +103,11 @@ def convert_default_value(rdef: _RdefRde
>       if isinstance(default, str) and rdef.object != 'String':
>           # real Strings can be anything,
>           # including things that look like keywords for other base types
> -        if str(rdef.object) in KEYWORD_MAP:
> -            try:
> -                return KEYWORD_MAP[str(rdef.object)][default.upper()]()
> -            except KeyError:
> -                # the default was likely not a special constant
> -                # like TODAY but some literal
> -                pass
> +        if str(rdef.object) in KEYWORD_MAP and default.upper() in KEYWORD_MAP[str(rdef.object)]:
> +            return KEYWORD_MAP[str(rdef.object)][default.upper()]()
> +        # else:
> +            # the default was likely not a special constant
> +            # like TODAY but some literal

Je ne suis pas sûr que ce soit une si bonne chose que cela en l'état. Je 
comprends l'idée d'enlever une exception "inutile". Cependant là est 
répété 2 fois les clés et c'est rapide de par la suite modifier à un 
endroit et d'oublier à l'autre. Je pense que c'est pour ça là que ce 
mécanisme moche avec exception a été utilisé.

>   
>           # bw compat for old schemas
>           if rdef.object in DATE_FACTORY_MAP:
> diff --git a/yams/schema.py b/yams/schema.py
> --- a/yams/schema.py
> +++ b/yams/schema.py
> @@ -279,10 +279,8 @@ class EntitySchema(PermissionMixIn, ERSc
>               pass
>   
>       def del_object_relation(self, rtype) -> None:
> -        try:
> +        if rtype in self.objrels:
>               del self.objrels[rtype]
> -        except KeyError:
> -            pass

Ça me paraîtrait mieux de faire "self.objrels.pop(rtype, None)" pour 
éviter de répéter la variable contenant la clé.
https://docs.python.org/3/library/stdtypes.html#dict.pop

>   
>       # IEntitySchema interface #################################################
>   
> @@ -627,9 +625,9 @@ class EntitySchema(PermissionMixIn, ERSc
>               required = card == '1'
>   
>               # check value according to their type
> -            try:
> +            if rschema in entity:
>                   value = entity[rschema]
> -            except KeyError:
> +            else:
>                   if creation and required:
>                       # missing required attribute with no default on creation
>                       # is not autorized
> @@ -685,9 +683,9 @@ class EntitySchema(PermissionMixIn, ERSc
>   
>       def convert_value(self, value: Any) -> Any:
>           """check the value of a final entity (ie a const value)"""
> -        try:
> +        if self.type in self.field_converters:
>               return self.field_converters[self.type](value)
> -        except KeyError:
> +        else:
>               return value
>   
>       def vocabulary(self, rtype: Union[str, _RelationSchemaType]) -> Tuple[str, ...]:
> @@ -1141,10 +1139,10 @@ class RelationSchema(ERSchema):
>           """
>           if etype is None:
>               return tuple(self._subj_schemas)
> -        try:
> +
> +        if etype in self._obj_schemas:
>               return tuple(self._obj_schemas[etype])
> -
> -        except KeyError:
> +        else:
>               raise KeyError("%s does not have %s as object" % (self, etype))
>   
>       def objects(self, etype: Optional[Union[_EntitySchemaType, str]] = None) ->\
> @@ -1174,9 +1172,9 @@ class RelationSchema(ERSchema):
>   
>       def rdef(self, subject: _EntitySchemaType, object: _EntitySchemaType) -> _RdefSchemaType:
>           """return the properties dictionary of a relation"""
> -        try:
> +        if (subject, object) in self.rdefs:
>               return self.rdefs[(subject, object)]
> -        except KeyError:
> +        else:
>               raise KeyError('%s %s %s' % (subject, self, object))
>   
>       def role_rdef(self, etype: _EntitySchemaType, ttype: Union[_EntitySchemaType, str],
> @@ -1242,9 +1240,9 @@ class Schema(object):
>               rschema._rehash()
>   
>       def get(self, name: str, default=None) -> Any:
> -        try:
> +        if name in self:
>               return self[name]
> -        except KeyError:
> +        else:
>               return default
>   
>       def __getitem__(self, name: str) -> Union[_EntitySchemaType, _RelationSchemaType]:
> @@ -1452,9 +1450,9 @@ class Schema(object):
>           :rtype: `EntitySchema`
>           :raise `KeyError`: if the type is not defined as an entity
>           """
> -        try:
> +        if etype in self._entities:
>               return self._entities[etype]
> -        except KeyError:
> +        else:
>               if isinstance(etype, tuple):
>                   etype = list(etype)
>               raise KeyError('No entity named %s in schema' % etype)
> @@ -1484,9 +1482,9 @@ class Schema(object):
>   
>           :rtype: `RelationSchema`
>           """
> -        try:
> +        if rtype in self._relations:
>               return self._relations[rtype]
> -        except KeyError:
> +        else:
>               raise KeyError('No relation named %s in schema' % rtype)
>   
>       def finalize(self) -> None:
> diff --git a/yams/schema2dot.py b/yams/schema2dot.py
> --- a/yams/schema2dot.py
> +++ b/yams/schema2dot.py
> @@ -280,9 +280,9 @@ def run() -> None:
>   
>       loader = SchemaLoader()
>   
> -    try:
> +    if sys.argv[1:]:
>           schema_dir = sys.argv[1]
> -    except IndexError:
> +    else:
>           print("USAGE: schema2dot SCHEMA_DIR [OUTPUT FILE]")
>           sys.exit(1)
>   
> 



More information about the cubicweb-devel mailing list