GSOC Phase 1 Late - Laying groundwork for practical aspects API
Five patches that made coala's aspects usable from other code: a constructor taking names, lookup errors, and get() callable from class or instance.
This post is part of my GSOC journey in coala.
The aspect module already had enough code to work on its own. What it did not
have was the boring part that makes a module usable from somewhere else. No
way to build one from the strings a user writes in a config file, no
consistent way to ask for a subaspect, and errors that leaked out of the
module as plain LookupError.
So this phase is groundwork. Five patches:
- AspectList: Follow class name convention
- AspectList: Overload
__init__to accept strings - Aspects: Create exception for aspects lookup
- AspectList: Add
get()method - aspectModule: Add
get()method
AspectList: Follow class name convention
The small one. Rename aspectlist into AspectList to conform with PEP8
class naming convention. Nothing else.
AspectList: Overload __init__ to accept strings
This one matters, because it is how a config file gets in. Users write aspect
names in their settings, so AspectList had to accept names and not only
aspect objects.
>>> AspectList(['coalaCorrect', 'aspectsYEAH'])
[<aspectclass '...coalaCorrect'>, <aspectclass '...aspectsYEAH'>]
The trick is a one-line change in super().__init__. Before, we checked every
item in seq to assert it was already an aspect object. Now we only check
whether it is one:
def __init__(self, seq=()):
"""
Initialize a new AspectList.
:param seq: A sequence of aspectclass, aspectclass
instance, or string of partial/full
qualified aspect name.
"""
super().__init__((item if isaspect(item) else
coalib.bearlib.aspects[item] for item in seq))
If it is an aspect, pass it through. If it is a string, look it up in the
aspects module and add the result. The doctests in the real patch cover the
mixed case too, AspectList([CommitMessage.Shortlog, 'CommitMessage.Body']).
Aspects: Create exception for aspects lookup
I moved the aspect exceptions into their own module to avoid circular imports
later, then made a set of LookupError subclasses to replace the bare
LookupError the aspect module used to raise.
The base class is the part I got slightly wrong:
class AspectLookupError(LookupError):
def __init__(self, aspectname, message=None):
self.aspectname = aspectname
if message is None:
message = ('Error when trying to search aspect named {}'
.format(repr(aspectname)))
super().__init__(message)
Fine when every raiser has a name to give. Then the next patch needed to raise
one where I had an aspect object and a custom message, so aspectname got
filled with a placeholder just to satisfy the signature. Writing both
aspectname and message as optional keyword arguments would have been
better. I was not sure enough to change it at the time.
AspectList: Add get() method
The long one. The goal:
>>> aspects = AspectList([Root.Smell.MethodSmell,
... Root.Smell.ClassSmell.DataClump()])
>>> aspects.get('MethodSmell')
<aspectclass 'Root.Smell.MethodSmell'>
>>> aspects.get('ClassSmell.DataClump')
<DataClump object(...) ...>
>>> aspects.get('BadSmell')
None
Bears could then ask whether an aspect is present and read its tastes:
class SomeBear(LocalBear, aspects={
'fix': Root.Metadata.CommitMessage
}):
def run(self, file, filename, aspects: AspectList = None):
commit_message = Root.Metadata.CommitMessage
shortlog = aspects.get(commit_message.ShortLog)
arg = ()
if shortlog:
arg += ('max_length=' + shortlog.max_length)
# run bear with arg or something
Split into two commits. First, a get() on aspectbase itself, so a single
aspect can hand out its own subaspects and AspectList.get() just loops over
its items and calls that. Otherwise the traversal logic gets written twice.
The first version worked from an aspect instance but not from the aspect
class, because self does not exist there. With help from
@userzimmerman I moved the logic to a
module-level function and wrapped it in a descriptor, so the same call works
from either:
class SubaspectGetter:
def __get__(self, obj, owner):
parent = obj if obj is not None else owner
return functools.partial(get_subaspect, parent)
class aspectbase:
get = SubaspectGetter()
A descriptor runs on attribute access and gets told whether it was reached through the class or an instance, which is exactly the bit of context we needed. Closest thing I know from elsewhere is a getter with extra logic attached to the class rather than the object.
>>> coala_aspects['metadata'].get('commitmessage')
<aspectclass '...CommitMessage'>
>>> coala_aspects['metadata']('py').get('commitmessage')
NotImplementedError: ...
The second line should have returned CommitMessage; it raised because of a
separate bug, which is why get_subaspect refuses to look up children of an
aspect instance for now:
if isinstance(parent, aspectbase):
raise NotImplementedError('Cannot access children of aspect '
'instance.')
I preferred an error to a wrong answer. Then AspectList.get() itself is
small, since the traversal already exists:
def get(self, aspect):
"""
Return first item that match or contain an aspect.
:param aspect: An aspectclass OR name of an aspect.
:return: An aspectclass OR aspectclass instance,
depend on
AspectList content. Return None if no
match found.
"""
if not isaspect(aspect):
aspect = coalib.bearlib.aspects[aspect]
try:
return next(filter(None,
(item.get(aspect) for item in self)))
except StopIteration:
return None
aspectModule: Add get() method
Last one, and mostly symmetry, so that all three places have a get() that
returns None instead of raising:
def get(self, aspectname):
"""
Search and get an aspectclass from string of full or partial
qualified name of the aspect.
:raise MultipleAspectFoundError:
When multiple aspects with same name was found.
:return:
An aspectclass or None.
"""
try:
return self[aspectname]
except AspectNotFoundError:
return None
Summary
The aspect API groundwork is more or less done. The next coding phase is implementing aspects in coala’s processing part, which is where the whole feature either works or does not.