Python builtins.__name__() Examples

The following are 30 code examples of builtins.__name__(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module builtins , or try the search function .
Example #1
Source File: test_util.py    From pex with Apache License 2.0 6 votes vote down vote up
def test_access_zipped_assets(
    mock_resource_string,
    mock_resource_isdir,
    mock_resource_listdir,
    mock_safe_mkdir,
    mock_safe_mkdtemp):

  mock_open = mock.mock_open()
  mock_safe_mkdtemp.side_effect = iter(['tmpJIMMEH', 'faketmpDir'])
  mock_resource_listdir.side_effect = iter([['./__init__.py', './directory/'], ['file.py']])
  mock_resource_isdir.side_effect = iter([False, True, False])
  mock_resource_string.return_value = 'testing'

  with mock.patch('%s.open' % python_builtins.__name__, mock_open, create=True):
    temp_dir = DistributionHelper.access_zipped_assets('twitter.common', 'dirutil')
    assert mock_resource_listdir.call_count == 2
    assert mock_open.call_count == 2
    file_handle = mock_open.return_value.__enter__.return_value
    assert file_handle.write.call_count == 2
    assert mock_safe_mkdtemp.mock_calls == [mock.call()]
    assert temp_dir == 'tmpJIMMEH'
    assert mock_safe_mkdir.mock_calls == [mock.call(os.path.join('tmpJIMMEH', 'directory'))] 
Example #2
Source File: gce_virtual_machine_test.py    From PerfKitBenchmarker with Apache License 2.0 6 votes vote down vote up
def PatchCriticalObjects(retvals=None):
  """A context manager that patches a few critical objects with mocks."""

  def ReturnVal(*unused_arg, **unused_kwargs):
    del unused_arg
    del unused_kwargs
    return ('', '', 0) if retvals is None else retvals.pop(0)

  with mock.patch(
      vm_util.__name__ + '.IssueCommand',
      side_effect=ReturnVal) as issue_command, mock.patch(
          builtins.__name__ + '.open'), mock.patch(
              vm_util.__name__ +
              '.NamedTemporaryFile'), mock.patch(util.__name__ +
                                                 '.GetDefaultProject'):
    yield issue_command 
Example #3
Source File: bases.py    From python-netsurv with MIT License 6 votes vote down vote up
def igetattr(self, name, context=None):
        """inferred getattr"""
        if not context:
            context = contextmod.InferenceContext()
        try:
            # avoid recursively inferring the same attr on the same class
            if context.push((self._proxied, name)):
                return

            # XXX frame should be self._proxied, or not ?
            get_attr = self.getattr(name, context, lookupclass=False)
            yield from _infer_stmts(
                self._wrap_attr(get_attr, context), context, frame=self
            )
        except exceptions.AttributeInferenceError as error:
            try:
                # fallback to class.igetattr since it has some logic to handle
                # descriptors
                # But only if the _proxied is the Class.
                if self._proxied.__class__.__name__ != "ClassDef":
                    raise exceptions.InferenceError(**vars(error)) from error
                attrs = self._proxied.igetattr(name, context, class_context=False)
                yield from self._wrap_attr(attrs, context)
            except exceptions.AttributeInferenceError as error:
                raise exceptions.InferenceError(**vars(error)) from error 
Example #4
Source File: serializer.py    From Hands-On-Application-Development-with-PyCharm with MIT License 6 votes vote down vote up
def serialize(self):
        # Serialize functools.partial() arguments
        func_string, func_imports = serializer_factory(self.value.func).serialize()
        args_string, args_imports = serializer_factory(self.value.args).serialize()
        keywords_string, keywords_imports = serializer_factory(self.value.keywords).serialize()
        # Add any imports needed by arguments
        imports = {'import functools', *func_imports, *args_imports, *keywords_imports}
        return (
            'functools.%s(%s, *%s, **%s)' % (
                self.value.__class__.__name__,
                func_string,
                args_string,
                keywords_string,
            ),
            imports,
        ) 
Example #5
Source File: node_classes.py    From python-netsurv with MIT License 6 votes vote down vote up
def __str__(self):
        rname = self._repr_name()
        cname = type(self).__name__
        if rname:
            string = "%(cname)s.%(rname)s(%(fields)s)"
            alignment = len(cname) + len(rname) + 2
        else:
            string = "%(cname)s(%(fields)s)"
            alignment = len(cname) + 1
        result = []
        for field in self._other_fields + self._astroid_fields:
            value = getattr(self, field)
            width = 80 - len(field) - alignment
            lines = pprint.pformat(value, indent=2, width=width).splitlines(True)

            inner = [lines[0]]
            for line in lines[1:]:
                inner.append(" " * alignment + line)
            result.append("%s=%s" % (field, "".join(inner)))

        return string % {
            "cname": cname,
            "rname": rname,
            "fields": (",\n" + " " * alignment).join(result),
        } 
Example #6
Source File: vinegar.py    From NoobSec-Toolkit with GNU General Public License v2.0 6 votes vote down vote up
def _get_exception_class(cls):
    if cls in _exception_classes_cache:
        return _exception_classes_cache[cls]

    # subclass the exception class' to provide a version of __str__ that supports _remote_tb
    class Derived(cls):
        def __str__(self):
            try:
                text = cls.__str__(self)
            except Exception:
                text = "<Unprintable exception>"
            if hasattr(self, "_remote_tb"):
                text += "\n\n========= Remote Traceback (%d) =========\n%s" % (
                    self._remote_tb.count("\n\n========= Remote Traceback") + 1, self._remote_tb)
            return text
        def __repr__(self):
            return str(self)
    
    Derived.__name__ = cls.__name__
    Derived.__module__ = cls.__module__
    _exception_classes_cache[cls] = Derived
    return Derived 
Example #7
Source File: raw_building.py    From python-netsurv with MIT License 6 votes vote down vote up
def inspect_build(self, module, modname=None, path=None):
        """build astroid from a living module (i.e. using inspect)
        this is used when there is no python source code available (either
        because it's a built-in module or because the .py is not available)
        """
        self._module = module
        if modname is None:
            modname = module.__name__
        try:
            node = build_module(modname, module.__doc__)
        except AttributeError:
            # in jython, java modules have no __doc__ (see #109562)
            node = build_module(modname)
        node.file = node.path = os.path.abspath(path) if path else path
        node.name = modname
        MANAGER.cache_module(node)
        node.package = hasattr(module, "__path__")
        self._done = {}
        self.object_build(node, module)
        return node 
Example #8
Source File: kubernetes_virtual_machine_test.py    From PerfKitBenchmarker with Apache License 2.0 6 votes vote down vote up
def patch_critical_objects(stdout='', stderr='', return_code=0, flags=FLAGS):
  with contextlib2.ExitStack() as stack:
    retval = (stdout, stderr, return_code)

    flags.gcloud_path = 'gcloud'
    flags.run_uri = _RUN_URI
    flags.kubectl = _KUBECTL
    flags.kubeconfig = _KUBECONFIG

    stack.enter_context(mock.patch(builtins.__name__ + '.open'))
    stack.enter_context(mock.patch(vm_util.__name__ + '.PrependTempDir'))

    # Save and return the temp_file mock here so that we can access the write()
    # call on the instance that the mock returned. This allows us to verify
    # that the body of the file is what we expect it to be (useful for
    # verifying that the pod.yml body was written correctly).
    temp_file = stack.enter_context(
        mock.patch(vm_util.__name__ + '.NamedTemporaryFile'))

    issue_command = stack.enter_context(
        mock.patch(vm_util.__name__ + '.IssueCommand', return_value=retval))

    yield issue_command, temp_file 
Example #9
Source File: serializer.py    From Hands-On-Application-Development-with-PyCharm with MIT License 6 votes vote down vote up
def serialize(self):
        if getattr(self.value, "__self__", None) and isinstance(self.value.__self__, type):
            klass = self.value.__self__
            module = klass.__module__
            return "%s.%s.%s" % (module, klass.__name__, self.value.__name__), {"import %s" % module}
        # Further error checking
        if self.value.__name__ == '<lambda>':
            raise ValueError("Cannot serialize function: lambda")
        if self.value.__module__ is None:
            raise ValueError("Cannot serialize function %r: No module" % self.value)

        module_name = self.value.__module__

        if '<' not in self.value.__qualname__:  # Qualname can include <locals>
            return '%s.%s' % (module_name, self.value.__qualname__), {'import %s' % self.value.__module__}

        raise ValueError(
            'Could not find function %s in %s.\n' % (self.value.__name__, module_name)
        ) 
Example #10
Source File: vinegar.py    From NoobSec-Toolkit with GNU General Public License v2.0 6 votes vote down vote up
def _get_exception_class(cls):
    if cls in _exception_classes_cache:
        return _exception_classes_cache[cls]

    # subclass the exception class' to provide a version of __str__ that supports _remote_tb
    class Derived(cls):
        def __str__(self):
            try:
                text = cls.__str__(self)
            except Exception:
                text = "<Unprintable exception>"
            if hasattr(self, "_remote_tb"):
                text += "\n\n========= Remote Traceback (%d) =========\n%s" % (
                    self._remote_tb.count("\n\n========= Remote Traceback") + 1, self._remote_tb)
            return text
        def __repr__(self):
            return str(self)
    
    Derived.__name__ = cls.__name__
    Derived.__module__ = cls.__module__
    _exception_classes_cache[cls] = Derived
    return Derived 
Example #11
Source File: objectmodel.py    From pySINDy with MIT License 6 votes vote down vote up
def __new__(cls, *args, **kwargs):
        # Append the values from the AGeneratorType unto this object.
        ret = super().__new__(cls, *args, **kwargs)
        astroid_builtins = astroid.MANAGER.astroid_cache[builtins.__name__]
        generator = astroid_builtins.get("async_generator")
        if generator is None:
            # Make it backward compatible.
            generator = astroid_builtins.get("generator")

        for name, values in generator.locals.items():
            method = values[0]
            patched = lambda cls, meth=method: meth

            setattr(type(ret), "py" + name, property(patched))

        return ret 
Example #12
Source File: exceptions.py    From python-netsurv with MIT License 6 votes vote down vote up
def visit_tuple(self, tuple_node):
        if PY3K or not tuple_node.elts:
            self._checker.add_message("raising-bad-type", node=self._node, args="tuple")
            return

        # On Python 2, using the following is not an error:
        #    raise (ZeroDivisionError, None)
        #    raise (ZeroDivisionError, )
        # What's left to do is to check that the first
        # argument is indeed an exception. Verifying the other arguments
        # is not the scope of this check.
        first = tuple_node.elts[0]
        inferred = utils.safe_infer(first)
        if not inferred or inferred is astroid.Uninferable:
            return

        if (
            isinstance(inferred, astroid.Instance)
            and inferred.__class__.__name__ != "Instance"
        ):
            # TODO: explain why
            self.visit_default(tuple_node)
        else:
            self.visit(inferred) 
Example #13
Source File: bases.py    From pySINDy with MIT License 6 votes vote down vote up
def _is_property(meth):
    if PROPERTIES.intersection(meth.decoratornames()):
        return True
    stripped = {
        name.split(".")[-1]
        for name in meth.decoratornames()
        if name is not util.Uninferable
    }
    if any(name in stripped for name in POSSIBLE_PROPERTIES):
        return True

    # Lookup for subclasses of *property*
    if not meth.decorators:
        return False
    for decorator in meth.decorators.nodes or ():
        inferred = helpers.safe_infer(decorator)
        if inferred is None or inferred is util.Uninferable:
            continue
        if inferred.__class__.__name__ == "ClassDef":
            for base_class in inferred.bases:
                module, _ = base_class.lookup(base_class.name)
                if module.name == BUILTINS and base_class.name == "property":
                    return True

    return False 
Example #14
Source File: raw_building.py    From python-netsurv with MIT License 6 votes vote down vote up
def inspect_build(self, module, modname=None, path=None):
        """build astroid from a living module (i.e. using inspect)
        this is used when there is no python source code available (either
        because it's a built-in module or because the .py is not available)
        """
        self._module = module
        if modname is None:
            modname = module.__name__
        try:
            node = build_module(modname, module.__doc__)
        except AttributeError:
            # in jython, java modules have no __doc__ (see #109562)
            node = build_module(modname)
        node.file = node.path = os.path.abspath(path) if path else path
        node.name = modname
        MANAGER.cache_module(node)
        node.package = hasattr(module, "__path__")
        self._done = {}
        self.object_build(node, module)
        return node 
Example #15
Source File: node_classes.py    From pySINDy with MIT License 6 votes vote down vote up
def __str__(self):
        rname = self._repr_name()
        cname = type(self).__name__
        if rname:
            string = "%(cname)s.%(rname)s(%(fields)s)"
            alignment = len(cname) + len(rname) + 2
        else:
            string = "%(cname)s(%(fields)s)"
            alignment = len(cname) + 1
        result = []
        for field in self._other_fields + self._astroid_fields:
            value = getattr(self, field)
            width = 80 - len(field) - alignment
            lines = pprint.pformat(value, indent=2, width=width).splitlines(True)

            inner = [lines[0]]
            for line in lines[1:]:
                inner.append(" " * alignment + line)
            result.append("%s=%s" % (field, "".join(inner)))

        return string % {
            "cname": cname,
            "rname": rname,
            "fields": (",\n" + " " * alignment).join(result),
        } 
Example #16
Source File: node_classes.py    From python-netsurv with MIT License 6 votes vote down vote up
def __str__(self):
        rname = self._repr_name()
        cname = type(self).__name__
        if rname:
            string = "%(cname)s.%(rname)s(%(fields)s)"
            alignment = len(cname) + len(rname) + 2
        else:
            string = "%(cname)s(%(fields)s)"
            alignment = len(cname) + 1
        result = []
        for field in self._other_fields + self._astroid_fields:
            value = getattr(self, field)
            width = 80 - len(field) - alignment
            lines = pprint.pformat(value, indent=2, width=width).splitlines(True)

            inner = [lines[0]]
            for line in lines[1:]:
                inner.append(" " * alignment + line)
            result.append("%s=%s" % (field, "".join(inner)))

        return string % {
            "cname": cname,
            "rname": rname,
            "fields": (",\n" + " " * alignment).join(result),
        } 
Example #17
Source File: raw_building.py    From pySINDy with MIT License 6 votes vote down vote up
def _astroid_bootstrapping(astroid_builtin=None):
    """astroid boot strapping the builtins module"""
    # this boot strapping is necessary since we need the Const nodes to
    # inspect_build builtins, and then we can proxy Const
    if astroid_builtin is None:
        astroid_builtin = Astroid_BUILDER.inspect_build(builtins)

    # pylint: disable=redefined-outer-name
    for cls, node_cls in node_classes.CONST_CLS.items():
        if cls is type(None):
            proxy = build_class("NoneType")
            proxy.parent = astroid_builtin
        elif cls is type(NotImplemented):
            proxy = build_class("NotImplementedType")
            proxy.parent = astroid_builtin
        else:
            proxy = astroid_builtin.getattr(cls.__name__)[0]
        if cls in (dict, list, set, tuple):
            node_cls._proxied = proxy
        else:
            _CONST_PROXY[cls] = proxy 
Example #18
Source File: raw_building.py    From pySINDy with MIT License 6 votes vote down vote up
def inspect_build(self, module, modname=None, path=None):
        """build astroid from a living module (i.e. using inspect)
        this is used when there is no python source code available (either
        because it's a built-in module or because the .py is not available)
        """
        self._module = module
        if modname is None:
            modname = module.__name__
        try:
            node = build_module(modname, module.__doc__)
        except AttributeError:
            # in jython, java modules have no __doc__ (see #109562)
            node = build_module(modname)
        node.file = node.path = os.path.abspath(path) if path else path
        node.name = modname
        MANAGER.cache_module(node)
        node.package = hasattr(module, "__path__")
        self._done = {}
        self.object_build(node, module)
        return node 
Example #19
Source File: bases.py    From python-netsurv with MIT License 6 votes vote down vote up
def igetattr(self, name, context=None):
        """inferred getattr"""
        if not context:
            context = contextmod.InferenceContext()
        try:
            # avoid recursively inferring the same attr on the same class
            if context.push((self._proxied, name)):
                return

            # XXX frame should be self._proxied, or not ?
            get_attr = self.getattr(name, context, lookupclass=False)
            yield from _infer_stmts(
                self._wrap_attr(get_attr, context), context, frame=self
            )
        except exceptions.AttributeInferenceError as error:
            try:
                # fallback to class.igetattr since it has some logic to handle
                # descriptors
                # But only if the _proxied is the Class.
                if self._proxied.__class__.__name__ != "ClassDef":
                    raise exceptions.InferenceError(**vars(error)) from error
                attrs = self._proxied.igetattr(name, context, class_context=False)
                yield from self._wrap_attr(attrs, context)
            except exceptions.AttributeInferenceError as error:
                raise exceptions.InferenceError(**vars(error)) from error 
Example #20
Source File: exceptions.py    From python-netsurv with MIT License 6 votes vote down vote up
def visit_tuple(self, tuple_node):
        if PY3K or not tuple_node.elts:
            self._checker.add_message("raising-bad-type", node=self._node, args="tuple")
            return

        # On Python 2, using the following is not an error:
        #    raise (ZeroDivisionError, None)
        #    raise (ZeroDivisionError, )
        # What's left to do is to check that the first
        # argument is indeed an exception. Verifying the other arguments
        # is not the scope of this check.
        first = tuple_node.elts[0]
        inferred = utils.safe_infer(first)
        if not inferred or inferred is astroid.Uninferable:
            return

        if (
            isinstance(inferred, astroid.Instance)
            and inferred.__class__.__name__ != "Instance"
        ):
            # TODO: explain why
            self.visit_default(tuple_node)
        else:
            self.visit(inferred) 
Example #21
Source File: bases.py    From pySINDy with MIT License 6 votes vote down vote up
def igetattr(self, name, context=None):
        """inferred getattr"""
        if not context:
            context = contextmod.InferenceContext()
        try:
            # avoid recursively inferring the same attr on the same class
            if context.push((self._proxied, name)):
                return

            # XXX frame should be self._proxied, or not ?
            get_attr = self.getattr(name, context, lookupclass=False)
            yield from _infer_stmts(
                self._wrap_attr(get_attr, context), context, frame=self
            )
        except exceptions.AttributeInferenceError as error:
            try:
                # fallback to class.igetattr since it has some logic to handle
                # descriptors
                # But only if the _proxied is the Class.
                if self._proxied.__class__.__name__ != "ClassDef":
                    raise exceptions.InferenceError(**vars(error)) from error
                attrs = self._proxied.igetattr(name, context, class_context=False)
                yield from self._wrap_attr(attrs, context)
            except exceptions.AttributeInferenceError as error:
                raise exceptions.InferenceError(**vars(error)) from error 
Example #22
Source File: serializer.py    From bioforum with MIT License 6 votes vote down vote up
def serialize(self):
        if getattr(self.value, "__self__", None) and isinstance(self.value.__self__, type):
            klass = self.value.__self__
            module = klass.__module__
            return "%s.%s.%s" % (module, klass.__name__, self.value.__name__), {"import %s" % module}
        # Further error checking
        if self.value.__name__ == '<lambda>':
            raise ValueError("Cannot serialize function: lambda")
        if self.value.__module__ is None:
            raise ValueError("Cannot serialize function %r: No module" % self.value)

        module_name = self.value.__module__

        if '<' not in self.value.__qualname__:  # Qualname can include <locals>
            return '%s.%s' % (module_name, self.value.__qualname__), {'import %s' % self.value.__module__}

        raise ValueError(
            'Could not find function %s in %s.\n' % (self.value.__name__, module_name)
        ) 
Example #23
Source File: objectmodel.py    From pySINDy with MIT License 6 votes vote down vote up
def __repr__(self):
        result = []
        cname = type(self).__name__
        string = "%(cname)s(%(fields)s)"
        alignment = len(cname) + 1
        for field in sorted(self.attributes()):
            width = 80 - len(field) - alignment
            lines = pprint.pformat(field, indent=2, width=width).splitlines(True)

            inner = [lines[0]]
            for line in lines[1:]:
                inner.append(" " * alignment + line)
            result.append(field)

        return string % {
            "cname": cname,
            "fields": (",\n" + " " * alignment).join(result),
        } 
Example #24
Source File: util.py    From python-hunter with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __get__(self, obj, cls):
        if obj is None:
            return self
        value = obj.__dict__[self.func.__name__] = self.func(obj)
        return value 
Example #25
Source File: raw_building.py    From pySINDy with MIT License 5 votes vote down vote up
def _add_dunder_class(func, member):
    """Add a __class__ member to the given func node, if we can determine it."""
    python_cls = member.__class__
    cls_name = getattr(python_cls, "__name__", None)
    if not cls_name:
        return
    cls_bases = [ancestor.__name__ for ancestor in python_cls.__bases__]
    ast_klass = build_class(cls_name, cls_bases, python_cls.__doc__)
    func.instance_attrs["__class__"] = [ast_klass] 
Example #26
Source File: raw_building.py    From pySINDy with MIT License 5 votes vote down vote up
def _io_discrepancy(member):
    # _io module names itself `io`: http://bugs.python.org/issue18602
    member_self = getattr(member, "__self__", None)
    return (
        member_self
        and inspect.ismodule(member_self)
        and member_self.__name__ == "_io"
        and member.__module__ == "io"
    ) 
Example #27
Source File: raw_building.py    From pySINDy with MIT License 5 votes vote down vote up
def _base_class_object_build(node, member, basenames, name=None, localname=None):
    """create astroid for a living class object, with a given set of base names
    (e.g. ancestors)
    """
    klass = build_class(
        name or getattr(member, "__name__", None) or localname,
        basenames,
        member.__doc__,
    )
    klass._newstyle = isinstance(member, type)
    node.add_local_node(klass, localname)
    try:
        # limit the instantiation trick since it's too dangerous
        # (such as infinite test execution...)
        # this at least resolves common case such as Exception.args,
        # OSError.errno
        if issubclass(member, Exception):
            instdict = member().__dict__
        else:
            raise TypeError
    except:  # pylint: disable=bare-except
        pass
    else:
        for item_name, obj in instdict.items():
            valnode = nodes.EmptyNode()
            valnode.object = obj
            valnode.parent = klass
            valnode.lineno = 1
            klass.instance_attrs[item_name] = [valnode]
    return klass 
Example #28
Source File: gce_virtual_machine_test.py    From PerfKitBenchmarker with Apache License 2.0 5 votes vote down vote up
def setUp(self):
    super(GceVirtualMachineTestCase, self).setUp()
    p = mock.patch(gce_virtual_machine.__name__ +
                   '.gce_network.GceNetwork.GetNetwork')
    self.mock_get_network = p.start()
    self.addCleanup(p.stop)
    p = mock.patch(gce_virtual_machine.__name__ +
                   '.gce_network.GceFirewall.GetFirewall')
    self.mock_get_firewall = p.start()
    self.addCleanup(p.stop)

    get_tmp_dir_mock = mock.patch(
        vm_util.__name__ + '.GetTempDir', return_value='TempDir')
    get_tmp_dir_mock.start()
    self.addCleanup(get_tmp_dir_mock.stop) 
Example #29
Source File: gce_virtual_machine_test.py    From PerfKitBenchmarker with Apache License 2.0 5 votes vote down vote up
def setUp(self):
    super(GceVirtualMachineOsTypesTestCase, self).setUp()
    FLAGS.gcp_instance_metadata_from_file = ''
    FLAGS.gcp_instance_metadata = ''
    FLAGS.gcloud_path = 'gcloud'

    p = mock.patch(gce_virtual_machine.__name__ +
                   '.gce_network.GceNetwork.GetNetwork')
    self.mock_get_network = p.start()
    self.addCleanup(p.stop)
    p = mock.patch(gce_virtual_machine.__name__ +
                   '.gce_network.GceFirewall.GetFirewall')

    self.mock_get_firewall = p.start()
    self.addCleanup(p.stop)
    self.spec = gce_virtual_machine.GceVmSpec(_COMPONENT,
                                              machine_type='fake-machine-type')
    p = mock.patch(gce_virtual_machine.__name__ +
                   '.linux_vm.BaseLinuxMixin._GetNumCpus')
    self.mock_get_num_cpus = p.start()
    self.addCleanup(p.stop)

    get_tmp_dir_mock = mock.patch(
        vm_util.__name__ + '.GetTempDir', return_value='TempDir')
    get_tmp_dir_mock.start()
    self.addCleanup(get_tmp_dir_mock.stop) 
Example #30
Source File: py_typecheck.py    From federated with Apache License 2.0 5 votes vote down vote up
def type_string(type_spec):
  """Creates a string representation of `type_spec` for error reporting.

  Args:
    type_spec: Either a Python type, or a tuple of Python types; the same as
      what's accepted by isinstance.

  Returns:
    A string representation for use in error reporting.

  Raises:
    TypeError: if the `type_spec` is not of the right type.
  """
  if isinstance(type_spec, type):
    if type_spec.__module__ == builtins.__name__:
      return type_spec.__name__
    else:
      return '{}.{}'.format(type_spec.__module__, type_spec.__name__)
  else:
    assert isinstance(type_spec, (tuple, list))
    type_names = [type_string(x) for x in type_spec]
    if len(type_names) == 1:
      return type_names[0]
    elif len(type_names) == 2:
      return '{} or {}'.format(*type_names)
    else:
      return ', '.join(type_names[0:-1] + ['or {}'.format(type_names[-1])])