1. Marc Abramowitz
  2. six_msabramo_misc

Commits

Marc Abramowitz  committed 039bbe9

Add get_function_qualname

  • Participants
  • Parent commits e3da7fd
  • Branches default

Comments (0)

Files changed (2)

File six.py

View file
 get_function_defaults = operator.attrgetter(_func_defaults)
 get_function_globals = operator.attrgetter(_func_globals)
 
+def get_function_qualname(func):
+    if hasattr(func, '__qualname__'): # a method in Python 3.3
+        return '%s.%s' % (
+            func.__module__, func.__qualname__)
+    if hasattr(func, 'im_class'):  # a method in Python 2
+        return '%s.%s.%s' % (
+            func.__module__, func.im_class.__name__, func.__name__)
+    if hasattr(func, '__self__'): # a method in Python 3.2
+        return '%s.%s.%s' % (
+            func.__module__, func.__self__.__class__.__name__, func.__name__)
+    else:  # a function
+        return '%s.%s' % (
+            func.__module__, func.__name__)
+
 
 def iterkeys(d, **kw):
     """Return an iterator over the keys of a dictionary."""

File test_six.py

View file
     py.test.raises(AttributeError, six.get_method_function, hasattr)
 
 
+class SomeClass(object):
+    def some_method(self):
+        pass
+
+def test_get_function_qualname():
+    obj = SomeClass()
+    assert six.get_function_qualname(obj.some_method) == "test_six.SomeClass.some_method"
+
+    if sys.version_info < (3, 2) or sys.version_info >= (3, 3):
+        # I can't figure out how to get this in Python 3.2
+        assert six.get_function_qualname(SomeClass.some_method) == "test_six.SomeClass.some_method"
+
+    py.test.raises(AttributeError, six.get_method_function, hasattr)
+
+
 def test_get_function_closure():
     def f():
         x = 42