Python: avoiding conflict of NumPy's unittest.py with local unittest.py - python

Has anyone else encountered the situation where they have written unit tests for their code into a file named unittest.py, and found it to conflict with NumPy's unittest.py module? In other words, if I write this to unittest.py in a local directory:
if __name__ == "__main__":
print "pre-import"
#import numpy
print "post-import"
Then (no surprises here):
% python unittest.py
pre-import
post-import
But if I do:
if __name__ == "__main__":
print "pre-import"
import numpy
print "post-import"
I get:
% python unittest.py
pre-import
Traceback (most recent call last):
File "unittest.py", line 3, in <module>
import numpy
File "/home/jbbrown/local_bin/python/lib/python2.7/site-packages/numpy/__init__.py", line 137, in <module>
import add_newdocs
File "/home/jbbrown/local_bin/python/lib/python2.7/site-packages/numpy/add_newdocs.py", line 9, in <module>
from numpy.lib import add_newdoc
File "/home/jbbrown/local_bin/python/lib/python2.7/site-packages/numpy/lib/__init__.py", line 4, in <module>
from type_check import *
File "/home/jbbrown/local_bin/python/lib/python2.7/site-packages/numpy/lib/type_check.py", line 8, in <module>
import numpy.core.numeric as _nx
File "/home/jbbrown/local_bin/python/lib/python2.7/site-packages/numpy/core/__init__.py", line 40, in <module>
from numpy.testing import Tester
File "/home/jbbrown/local_bin/python/lib/python2.7/site-packages/numpy/testing/__init__.py", line 8, in <module>
from unittest import TestCase
ImportError: cannot import name TestCase
Subsequently, iPython fails to load:
% ipython
WARNING: IPython History requires SQLite, your history will not be saved
Traceback (most recent call last):
File "/home/jbbrown/local_bin/python/bin/ipython", line 7, in <module>
launch_new_instance()
File "/home/jbbrown/local_bin/python/lib/python2.7/site-packages/IPython/frontend/terminal/ipapp.py", line 402, in launch_new_instance
app.initialize()
File "<string>", line 2, in initialize
File "/home/jbbrown/local_bin/python/lib/python2.7/site-packages/IPython/config/application.py", line 84, in catch_config_error
return method(app, *args, **kwargs)
File "/home/jbbrown/local_bin/python/lib/python2.7/site-packages/IPython/frontend/terminal/ipapp.py", line 312, in initialize
self.init_shell()
File "/home/jbbrown/local_bin/python/lib/python2.7/site-packages/IPython/frontend/terminal/ipapp.py", line 332, in init_shell
ipython_dir=self.ipython_dir)
File "/home/jbbrown/local_bin/python/lib/python2.7/site-packages/IPython/config/configurable.py", line 318, in instance
inst = cls(*args, **kwargs)
File "/home/jbbrown/local_bin/python/lib/python2.7/site-packages/IPython/frontend/terminal/interactiveshell.py", line 183, in __init__
user_module=user_module, custom_exceptions=custom_exceptions
File "/home/jbbrown/local_bin/python/lib/python2.7/site-packages/IPython/core/interactiveshell.py", line 478, in __init__
self.init_reload_doctest()
File "/home/jbbrown/local_bin/python/lib/python2.7/site-packages/IPython/core/interactiveshell.py", line 662, in init_reload_doctest
doctest_reload()
File "/home/jbbrown/local_bin/python/lib/python2.7/site-packages/IPython/utils/doctestreload.py", line 72, in doctest_reload
import doctest
File "/home/jbbrown/local_bin/python/lib/python2.7/doctest.py", line 2118, in <module>
class DocTestCase(unittest.TestCase):
AttributeError: 'module' object has no attribute 'TestCase'
If you suspect this is an IPython bug, please report it at:
https://github.com/ipython/ipython/issues
or send an email to the mailing list at ipython-dev#scipy.org
You can print a more detailed traceback right now with "%tb", or use "%debug"
to interactively debug it.
Extra-detailed tracebacks for bug-reporting purposes can be enabled via:
c.Application.verbose_crash=True
Interestingly, if I move the import statement outside of the "if __name__" suite, e.g.,
print "pre-import"
import numpy
print "post-import"
if __name__ == "__main__":
pass
I get:
% python unittest.py
pre-import
pre-import
post-import
Traceback (most recent call last):
File "unittest.py", line 2, in <module>
import numpy
File "/home/jbbrown/local_bin/python/lib/python2.7/site-packages/numpy/__init__.py", line 137, in <module>
import add_newdocs
File "/home/jbbrown/local_bin/python/lib/python2.7/site-packages/numpy/add_newdocs.py", line 9, in <module>
from numpy.lib import add_newdoc
File "/home/jbbrown/local_bin/python/lib/python2.7/site-packages/numpy/lib/__init__.py", line 4, in <module>
from type_check import *
File "/home/jbbrown/local_bin/python/lib/python2.7/site-packages/numpy/lib/type_check.py", line 8, in <module>
import numpy.core.numeric as _nx
File "/home/jbbrown/local_bin/python/lib/python2.7/site-packages/numpy/core/__init__.py", line 40, in <module>
from numpy.testing import Tester
File "/home/jbbrown/local_bin/python/lib/python2.7/site-packages/numpy/testing/__init__.py", line 8, in <module>
from unittest import TestCase
ImportError: cannot import name TestCase
Of course it is trivial to change the name of the file containing my unit tests and avoid this, but I wonder if anyone else encountered this and thought of an elegant workaround that doesn't include renaming their unit test file?

You can switch to absolute imports by default on Python versions newer than 2.7:
from __future__ import absolute_import
if __name__ == "__main__":
print "pre-import"
import numpy
print "post-import"

Related

Numpy is Not a Generic Class

I am trying to learn Python and following along some modules. I am using Anaconda Powershell Prompt and using Python 3.7 from there. I am trying to follow along via the code below.
Everything works until I get to the line
from wrf import getvar
When I do that line I receive this
>>> from wrf import getvar
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\Paul\anaconda3\lib\site-packages\wrf\__init__.py", line 6, in <module>
from . import api
File "C:\Users\Paul\anaconda3\lib\site-packages\wrf\api.py", line 1, in <module>
from .config import (xarray_enabled, disable_xarray, enable_xarray,
File "C:\Users\Paul\anaconda3\lib\site-packages\wrf\config.py", line 62, in <module>
_init_local()
File "C:\Users\Paul\anaconda3\lib\site-packages\wrf\config.py", line 52, in _init_local
_try_enable_xarray()
File "C:\Users\Paul\anaconda3\lib\site-packages\wrf\config.py", line 17, in _try_enable_xarray
from xarray import DataArray
File "C:\Users\Paul\anaconda3\lib\site-packages\xarray\__init__.py", line 1, in <module>
from . import testing, tutorial
File "C:\Users\Paul\anaconda3\lib\site-packages\xarray\testing.py", line 9, in <module>
from xarray.core import duck_array_ops, formatting, utils
File "C:\Users\Paul\anaconda3\lib\site-packages\xarray\core\duck_array_ops.py", line 26, in <module>
from . import dask_array_compat, dask_array_ops, dtypes, npcompat, nputils
File "C:\Users\Paul\anaconda3\lib\site-packages\xarray\core\npcompat.py", line 72, in <module>
_SupportsDType[np.dtype],
File "C:\Users\Paul\anaconda3\lib\typing.py", line 275, in inner
return func(*args, **kwds)
File "C:\Users\Paul\anaconda3\lib\typing.py", line 999, in __class_getitem__
_check_generic(cls, params, len(cls.__parameters__))
File "C:\Users\Paul\anaconda3\lib\typing.py", line 209, in _check_generic
raise TypeError(f"{cls} is not a generic class")
TypeError: <class 'numpy.typing._dtype_like._SupportsDType'> is not a generic class
Looks like the last few lines return an error but as a beginner I have zero clue what this means.
This looks like a similar error to <class 'numpy.typing._dtype_like._SupportsDType'> is not a generic class when importing the plotly.express library - an incompatibility between wrf-python and numpy.
Try upgrading those libraries to the latest versions.

I am testing HTTP get method but there is an error "No module named ASCII"?

ASCII is installed but still getting this error. I tested by importing all the libraries in the error msg but could not solve it.
Complete Error Message here.
Traceback (most recent call last):
File "re.py", line 1, in <module>
import requests,compile, ASCII
File "C:\Program Files\Python37\lib\site-packages\requests\__init__.py", line 43, in <module>
import urllib3
File "C:\Program Files\Python37\lib\site-packages\urllib3\__init__.py", line 7, in <module>
from .connectionpool import HTTPConnectionPool, HTTPSConnectionPool, connection_from_url
File "C:\Program Files\Python37\lib\site-packages\urllib3\connectionpool.py", line 3, in <module>
import logging
File "C:\Program Files\Python37\lib\logging\__init__.py", line 26, in <module>
import sys, os, time, io, traceback, warnings, weakref, collections.abc
File "C:\Program Files\Python37\lib\traceback.py", line 5, in <module>
import linecache
File "C:\Program Files\Python37\lib\linecache.py", line 11, in <module>
import tokenize
File "C:\Program Files\Python37\lib\tokenize.py", line 33, in <module>
import re
File "C:\Users\naeem\Desktop\re.py", line 1, in <module>
import requests,compile, ASCII
ModuleNotFoundError: No module named 'ASCII'
Python Code I am running is here:
import requests,compile, ASCII
def main():
res = requests.get("https://www.google.com/")
print(res.text)
if __name__=="__main__":
main()
Can anybody help me out please?
ModuleNotFoundError: No module named 'ASCII'
This means that don't exist a module named 'ASCII'.
Maybe it's useful curses.ascii
so:
import curses.ascii
You can find Documentation here:
https://docs.python.org/3/library/curses.ascii.html

Module not found when using scipy

I have recently properly installed numpy and scipy. The following line runs without error.
import scipy
I am experiencing difficulty using scipy.io.wavefile. I have been trying to use the code from the "best answer" of this post.
However, when I try the first line,
from scipy.io import wavfile
I receive the following error and traceback,
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
from scipy.io import wavfile
File "C:\Users\Me\AppData\Local\Programs\Python\Python37-32\lib\site-packages\scipy\io\__init__.py", line 97, in <module>
from .matlab import loadmat, savemat, whosmat, byteordercodes
File "C:\Users\Me\AppData\Local\Programs\Python\Python37-32\lib\site-packages\scipy\io\matlab\__init__.py", line 13, in <module>
from .mio import loadmat, savemat, whosmat
File "C:\Users\Me\AppData\Local\Programs\Python\Python37-32\lib\site-packages\scipy\io\matlab\mio.py", line 12, in <module>
from .miobase import get_matfile_version, docfiller
File "C:\Users\Me\AppData\Local\Programs\Python\Python37-32\lib\site-packages\scipy\io\matlab\miobase.py", line 22, in <module>
from scipy.misc import doccer
File "C:\Users\Me\AppData\Local\Programs\Python\Python37-32\lib\site-packages\scipy\misc\__init__.py", line 68, in <module>
from scipy.interpolate._pade import pade as _pade
File "C:\Users\Me\AppData\Local\Programs\Python\Python37-32\lib\site-packages\scipy\interpolate\__init__.py", line 175, in <module>
from .interpolate import *
File "C:\Users\Me\AppData\Local\Programs\Python\Python37-32\lib\site-packages\scipy\interpolate\interpolate.py", line 21, in <module>
import scipy.special as spec
File "C:\Users\Me\AppData\Local\Programs\Python\Python37-32\lib\site-packages\scipy\special\__init__.py", line 640, in <module>
from ._ufuncs import *
File "_ufuncs.pyx", line 1, in init scipy.special._ufuncs
ImportError: DLL load failed: The specified module could not be found.
I also receive an error and traceback if I try the following line instead,
import scipy.io.wavfile
receiving a different response,
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
import scipy.io.wavfile
File "C:\Users\Me\AppData\Local\Programs\Python\Python37-32\lib\site-packages\scipy\io\__init__.py", line 97, in <module>
from .matlab import loadmat, savemat, whosmat, byteordercodes
File "C:\Users\Me\AppData\Local\Programs\Python\Python37-32\lib\site-packages\scipy\io\matlab\__init__.py", line 13, in <module>
from .mio import loadmat, savemat, whosmat
File "C:\Users\Me\AppData\Local\Programs\Python\Python37-32\lib\site-packages\scipy\io\matlab\mio.py", line 12, in <module>
from .miobase import get_matfile_version, docfiller
File "C:\Users\Me\AppData\Local\Programs\Python\Python37-32\lib\site-packages\scipy\io\matlab\miobase.py", line 22, in <module>
from scipy.misc import doccer
File "C:\Users\Me\AppData\Local\Programs\Python\Python37-32\lib\site-packages\scipy\misc\__init__.py", line 68, in <module>
from scipy.interpolate._pade import pade as _pade
File "C:\Users\Me\AppData\Local\Programs\Python\Python37-32\lib\site-packages\scipy\interpolate\__init__.py", line 175, in <module>
from .interpolate import *
File "C:\Users\Me\AppData\Local\Programs\Python\Python37-32\lib\site-packages\scipy\interpolate\interpolate.py", line 21, in <module>
import scipy.special as spec
File "C:\Users\Me\AppData\Local\Programs\Python\Python37-32\lib\site-packages\scipy\special\__init__.py", line 642, in <module>
from .basic import *
File "C:\Users\Me\AppData\Local\Programs\Python\Python37-32\lib\site-packages\scipy\special\basic.py", line 15, in <module>
from ._ufuncs import (ellipkm1, mathieu_a, mathieu_b, iv, jv, gamma,
ImportError: cannot import name 'ellipkm1' from 'scipy.special._ufuncs' (unknown location)
I do not understand why the module can not be found, if scipy is properly installed and can be imported by itself. I am using python 3.7.1. Could the code from the post be depreciated?
Apologies in advance for the long post.
Both error messages are complaining about the scipy.special._ufuncs module and a quick search revealed a few other posts, like this one, that suggest making sure you have the Visual C++ Redistributable Packages installed: https://www.microsoft.com/en-us/download/details.aspx?id=48145

Test framework quits unexpectedly - IntelliJ python plugin

I'm having a big problem with the testing framework in IntelliJ using with the python plugin.
When I launch my tests, written using unittest, the tests fail with an import error in the _jb_test_runner file.
I surfed the net for a while, but didn't get a useful solution. See the stacktrace below:
/usr/bin/python3.5 /home/davide/.IntelliJIdea2017.1/config/plugins/python/helpers/pycharm/_jb_unittest_runner.py --path /home/davide/Scrivania/musical-store/test/types/test_person.py
Testing started at 12.35 ...
Traceback (most recent call last):
File "/home/davide/.IntelliJIdea2017.1/config/plugins/python/helpers/pycharm/_jb_unittest_runner.py", line 4, in <module>
from unittest import main
File "/usr/lib/python3.5/unittest/__init__.py", line 58, in <module>
from .result import TestResult
File "/usr/lib/python3.5/unittest/result.py", line 5, in <module>
import traceback
File "/usr/lib/python3.5/traceback.py", line 5, in <module>
import linecache
File "/usr/lib/python3.5/linecache.py", line 8, in <module>
import functools
File "/usr/lib/python3.5/functools.py", line 22, in <module>
from types import MappingProxyType
ImportError: cannot import name 'MappingProxyType'
Error in sys.excepthook:
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/apport_python_hook.py", line 62, in apport_excepthook
import re, traceback
File "/usr/lib/python3.5/traceback.py", line 5, in <module>
import linecache
File "/usr/lib/python3.5/linecache.py", line 8, in <module>
import functools
File "/usr/lib/python3.5/functools.py", line 22, in <module>
from types import MappingProxyType
ImportError: cannot import name 'MappingProxyType'
Original exception was:
Traceback (most recent call last):
File "/home/davide/.IntelliJIdea2017.1/config/plugins/python/helpers/pycharm/_jb_unittest_runner.py", line 4, in <module>
from unittest import main
File "/usr/lib/python3.5/unittest/__init__.py", line 58, in <module>
from .result import TestResult
File "/usr/lib/python3.5/unittest/result.py", line 5, in <module>
import traceback
File "/usr/lib/python3.5/traceback.py", line 5, in <module>
import linecache
File "/usr/lib/python3.5/linecache.py", line 8, in <module>
import functools
File "/usr/lib/python3.5/functools.py", line 22, in <module>
from types import MappingProxyType
ImportError: cannot import name 'MappingProxyType'
Process finished with exit code 1
The code does not present any syntax error, but the problem started after a refactoring of the whole project I'm working on.
Thanks in advance.

Error after "from new import instancemethod" when importing scipy.stats

I am getting an exception from scipy whenever I try to import the nltk package. The command and the error looks like this:
>>> import nltk
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/nltk/__init__.py", line 114, in <module>
from nltk.collocations import *
File "/usr/local/lib/python2.7/dist-packages/nltk/collocations.py", line 39, in <module>
from nltk.metrics import ContingencyMeasures, BigramAssocMeasures, TrigramAssocMeasures
File "/usr/local/lib/python2.7/dist-packages/nltk/metrics/__init__.py", line 16, in <module>
from nltk.metrics.scores import (accuracy, precision, recall, f_measure,
File "/usr/local/lib/python2.7/dist-packages/nltk/metrics/scores.py", line 16, in <module>
from scipy.stats.stats import betai
File "/usr/local/lib/python2.7/dist-packages/scipy/stats/__init__.py", line 344, in <module>
from .stats import *
File "/usr/local/lib/python2.7/dist-packages/scipy/stats/stats.py", line 176, in <module>
from . import distributions
File "/usr/local/lib/python2.7/dist-packages/scipy/stats/distributions.py", line 10, in <module>
from ._distn_infrastructure import (entropy, rv_discrete, rv_continuous,
File "/usr/local/lib/python2.7/dist-packages/scipy/stats/_distn_infrastructure.py", line 43, in <module>
from new import instancemethod
File "new.py", line 107
return copy.deepcopy(self)
^
IndentationError: expected an indented block
I executed this command in a terminal (ubuntu 16.04 LTS system). I did not find anything about this error and the indentation doesn't look wrong.
The SyntaxError is in your file new.py (I guess it's in your current working directory). Try to switch to a directory where no new.py file is present (or move the new.py file in another directory), then the internal scipy import should work without problems.
On the other hand you can just upgrade to scipy 0.19.x. They removed the import there and it should work without problems.
Note that it's always a bad idea to name python files like builtin-modules! That's a common source for exceptions or unexpected behaviour.

Categories