Add utils.qualname. Closes #169.

This commit is contained in:
Florian Bruhin 2014-10-08 21:11:04 +02:00
parent b5b240c3f6
commit 71308b45ac
5 changed files with 37 additions and 10 deletions

View File

@ -658,7 +658,7 @@ class Application(QApplication):
to_save.append(("cookies", cookie_jar.save)) to_save.append(("cookies", cookie_jar.save))
for what, handler in to_save: for what, handler in to_save:
log.destroy.debug("Saving {} (handler: {})".format( log.destroy.debug("Saving {} (handler: {})".format(
what, handler.__qualname__)) what, utils.qualname(handler)))
try: try:
handler() handler()
except AttributeError as e: except AttributeError as e:

View File

@ -335,7 +335,7 @@ class ConfigManager(QObject):
func() func()
else: else:
raise TypeError("Handler {} has invalid signature.".format( raise TypeError("Handler {} has invalid signature.".format(
func.__qualname__)) utils.qualname(func)))
for handler in to_delete: for handler in to_delete:
change_handlers.remove(handler) change_handlers.remove(handler)

View File

@ -201,7 +201,7 @@ class ModeManager(QObject):
handler = self._handlers[curmode] handler = self._handlers[curmode]
if curmode != usertypes.KeyMode.insert: if curmode != usertypes.KeyMode.insert:
log.modes.debug("got keypress in mode {} - calling handler " log.modes.debug("got keypress in mode {} - calling handler "
"{}".format(curmode, handler.__qualname__)) "{}".format(curmode, utils.qualname(handler)))
handled = handler(event) if handler is not None else False handled = handler(event) if handler is not None else False
is_non_alnum = bool(event.modifiers()) or not event.text().strip() is_non_alnum = bool(event.modifiers()) or not event.text().strip()

View File

@ -35,7 +35,7 @@ def log_events(klass):
@functools.wraps(old_event) @functools.wraps(old_event)
def new_event(self, e, *args, **kwargs): def new_event(self, e, *args, **kwargs):
"""Wrapper for event() which logs events.""" """Wrapper for event() which logs events."""
log.misc.debug("Event in {}: {}".format(klass.__name__, log.misc.debug("Event in {}: {}".format(utils.qualname(klass),
qenum_key(QEvent, e.type()))) qenum_key(QEvent, e.type())))
return old_event(self, e, *args, **kwargs) return old_event(self, e, *args, **kwargs)
@ -201,10 +201,7 @@ def format_call(func, args=None, kwargs=None, full=True):
A string with the function call. A string with the function call.
""" """
if full: if full:
if func.__module__ is not None: name = utils.qualname(func)
name = '.'.join([func.__module__, func.__qualname__])
else:
name = func.__qualname__
else: else:
name = func.__name__ name = func.__name__
return '{}({})'.format(name, _format_args(args, kwargs)) return '{}({})'.format(name, _format_args(args, kwargs))

View File

@ -23,6 +23,7 @@ import io
import sys import sys
import enum import enum
import shlex import shlex
import inspect
import os.path import os.path
import urllib.request import urllib.request
import urllib.parse import urllib.parse
@ -532,7 +533,7 @@ class prevent_exceptions: # pylint: disable=invalid-name
try: try:
return func(*args, **kwargs) return func(*args, **kwargs)
except BaseException: except BaseException:
log.misc.exception("Error in {}".format(func.__qualname__)) log.misc.exception("Error in {}".format(qualname(func)))
return retval return retval
return wrapper return wrapper
@ -555,7 +556,7 @@ def get_repr(obj, constructor=False, **attrs):
<Foo one=1 two=2>. <Foo one=1 two=2>.
attrs: The attributes to add. attrs: The attributes to add.
""" """
cls = getattr(obj.__class__, '__qualname__', obj.__class__.__name__) cls = qualname(obj.__class__)
parts = [] parts = []
for name, val in attrs.items(): for name, val in attrs.items():
parts.append('{}={!r}'.format(name, val)) parts.append('{}={!r}'.format(name, val))
@ -566,3 +567,32 @@ def get_repr(obj, constructor=False, **attrs):
return '<{} {}>'.format(cls, ' '.join(parts)) return '<{} {}>'.format(cls, ' '.join(parts))
else: else:
return '<{}>'.format(cls) return '<{}>'.format(cls)
def qualname(obj):
"""Get the fully qualified name of an object.
Based on twisted.python.reflect.fullyQualifiedName.
Should work with:
- functools.partial objects
- functions
- classes
- methods
- modules
"""
if isinstance(obj, functools.partial):
obj = obj.func
if hasattr(obj, '__qualname__'):
name = obj.__qualname__
elif hasattr(obj, '__name__'):
name = obj.__name__
else:
name = '<unknown>'
if inspect.isclass(obj) or inspect.isfunction(obj):
module = obj.__module__
return "{}.{}".format(module, name)
elif inspect.ismethod(obj):
return "{}.{}".format(obj.__module__, name)
else:
return name