Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot import name 'MappingProxyType' error after importing functools

After I import functools I receive such message from interpreter:

Traceback (most recent call last): File "C:/Users/Admin/Documents/Python/decorator.py", line 1, in import functools File "C:\Python3\lib\functools.py", line 22, in from types import MappingProxyType ImportError: cannot import name 'MappingProxyType'

import functools


def trace(func):
    def inner(*args, **kwargs):
        print(func.__name__, args, kwargs)
        return func(*args, **kwargs)
    functools.update_wrapper(inner, func)
    return inner


@trace
def foo(x):
    return x


foo(42)

Using PyCharm as IDE and CPython as interpreter

like image 363
Kirill Korolev Avatar asked Apr 17 '17 14:04

Kirill Korolev


2 Answers

This is not a real answer, but a comment.

First: I can't verify the problem presented: The code within the question works perfectly in the standard python I am using.

Second: I stumbled upon this question because I had the same error message, but maybe for a different reason. I accidentally named a module "type". Strangely the python framework selected this new "type" module while resolving references from within imported system modules. Which indicates that python's algorithm of resolving references is a bit ... well ... of a bit of very simple design.

Nevertheless if readers get this error message please check first if you accidentally named something "type" somewhere in your code as a first approach to solve the problem before checking other reasons for that error message.

Update: This is a quite common phenomenon in Python. Be careful! Whenever you give your module a name that has already been used for any imported Python module (and you might not be aware of these names!) you will have the chance of getting strange errors more or less similar to the one described in the question.

like image 78
Regis May Avatar answered Oct 17 '22 16:10

Regis May


The accepted solution forces you to rename your module, but:

There's nothing wrong with having a module named types in your package, actually you'll get this error if the interpreter is run with either the current directory or a PYTHONPATH directory is set to the directory containing the module.

If you avoid this situation, you won't have to rename your module.

If you use an IDE, check the run configuration to make sure PYTHONPATH or current directory isn't set to include your modules.

like image 27
CharlesB Avatar answered Oct 17 '22 14:10

CharlesB