I'm trying to reach 100% testing coverage in a bit of code that I'm writing. The following block of code, however, is giving me trouble.
try:
from south.modelsinspector import add_introspection_rules
add_introspection_rules([], ["^localized_recurrence\.duration_field\.DurationField"])
except ImportError:
pass
The code above is part of my module under test. I need to create a test (without modifying the code above) which follows the ImportError branch.
How can I programmatically cause the ImportError to occur, while only writing code in my tests?
I'd try patching sys.modules and replacing south.modelsinspector with a mock module.
See the docs on Import statement for inspiration.
In [1]: from re import sub
In [2]: import sys
In [3]: sys.modules['re'] = {}
In [4]: from re import sub
---------------------------------------------------------------------------
ImportError Traceback (most recent call last)
/home/kos/codility/frontend_v2/<ipython-input-4-6d4794835d43> in <module>()
----> 1 from re import sub
ImportError: cannot import name sub
You can do it in a narrow context by using mock.patch.dict (as a test decorator or context manager):
In [6]: with mock.patch.dict('sys.modules', {'re': {}}):
from re import sub
...:
---------------------------------------------------------------------------
ImportError Traceback (most recent call last)
<ipython-input-6-7479025ab931> in <module>()
1 with mock.patch.dict('sys.modules', {'re': {}}):
----> 2 from re import sub
3
ImportError: cannot import name sub
In [8]: from re import sub
In [9]:
You can change sys.path for the test. For example:
>>>import bs4
>>>
>>>import sys
>>>p=sys.path
>>>sys.path=['']
>>>import bs4
ImportError: No module named bs4
>>>sys.path=p
>>>import bs4
>>>
Just modify sys.path for that specific test on setUp() and later on tearDown() restore it.
Hope this helps!
Related
I keep getting this error code from my Jupyter Notebook and there is little to no explanation.
After inputting:
from nltk import pos_tag, RegexpParser
from tokenize_words import word_sentence_tokenize
from chunk_counters import np_chunk_counter, vp_chunk_counter
I get:
---------------------------------------------------------------------------
ModuleNotFoundError Traceback (most recent call last)
<ipython-input-14-a5041508c9f2> in <module>
1 from nltk import pos_tag, RegexpParser
----> 2 from tokenize_words import word_sentence_tokenize
3 from chunk_counters import np_chunk_counter, vp_chunk_counter
ModuleNotFoundError: No module named 'tokenize_words'
The full lesson allows the student to follow along with Jupyter. I don't know why but all it ever gives me is module not found error codes.
Is there a way I can store my import packages inside a module and then run said module to load the packages? Something like below:
# Store imports in a module
def LoadPackages():
import pandas as pd
import numpy as np
...
# Run module to load packages
LoadPackages()
I tried this and I got the below error:
d = {'col1': [1, 2], 'col2': [3, 4]}
df = pd.DataFrame(data=d)
df
NameError: name 'pd' is not defined
Declare the variable names as global in the function and the imports will be bound to variable names in the module's global scope.
>>> def LoadPackages():
... global pd, np
... import pandas as pd
... import numpy as np
...
>>> pd.DataFrame()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'pd' is not defined
>>>
>>>
>>> LoadPackages()
>>> pd.DataFrame
<class 'pandas.core.frame.DataFrame'>
>>>
You can have another python file called "modules.py" and inside that file you can add
import pandas as pd
import numpy as np
Then in your other python file all you will need to do is import that initial file using
import modules
of course the drawback here is you will always need to call all functions or objects using modules.pd.etc so it would be best to use
from modules import pd, np, #rest of modules
I guess you can just have a file called modules.py, and inside it you put your imports. Then you import it like this in your other files:
from module import *
No, it is only imported if and only if the function is executed.
If you may only run a function very rarely and don't need the module imported anywhere else, it may be beneficial to only import it in that function. Or if there is a name clash or other reason you don't want the module or symbols from the module available everywhere, you may only want to import it in a specific function
for example:
def LoadPackages():
import requests
res = requests.get("https://google.com")
print(res)
LoadPackages()
res = requests.get("https://google.com")
Output is:
**<Response [200]>**
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-23-b435c28bc51c> in <module>
1 LoadPackages()
2
----> 3 res = requests.get("https://google.com")
NameError: name 'requests' is not defined
Here requests library is imported inside the function scope and successfully performed the "GET" request. And when I made the "GET" request outside function I get the import error.
I have this
folder_tree
and i want to import class from runner.py in crawlers.py
from scraper.runner import Runner
runner = Runner([{'name': 'my_name', 'urls': ["https://www.exaple.com/"]}])
runner.crawl()
but i got error
Traceback (most recent call last):
File "./scraper/crawlers/actor_crawler.py", line 3, in <module>
from scraper.runner import Runner
ModuleNotFoundError: No module named 'scraper'
Also, i tried relative import:
from ..runner import Runner
And got that:
ValueError: attempted relative import beyond top-level package
I've found the following link to be incredibly helpful in understanding how Python does imports.
The surefire way to ensure your module can be imported though is adding it to os.syspath. Try adding the following to the beginning of your script:
import os
import sys
sys.path.append(/path/to/scraper/scraper/runner.py)
from scraper.runner import Runner
runner = Runner([{'name': 'my_name', 'urls': ["https://www.exaple.com/"]}])
runner.crawl()
I'm tyring to import the "gleam" package in Python 3. I have installed the "gleam" package successfully, but still it showing error.
from wtforms import fields
from ggplot import *
from gleam import Page, panels
class ScatterInput(panels.Inputs):
title = fields.StringField(label="Title of plot:")
yvar = fields.SelectField(label="Y axis",
choices=[("beef", "Beef"),
("pork", "Pork")])
smoother = fields.BooleanField(label="Smoothing Curve")
class ScatterPlot(panels.Plot):
name = "Scatter"
def plot(self, inputs):
p = ggplot(meat, aes(x='date', y=inputs.yvar))
if inputs.smoother:
p = p + stat_smooth(color="blue")
p = p + geom_point() + ggtitle(inputs.title)
return p
class ScatterPage(Page):
input = ScatterInput()
output = ScatterPlot()
ScatterPage.run()
Error:
ModuleNotFoundError - Traceback (most> recent call last) in ()
----> 1 import gleam
C:\pythonNJ\lib\site-packages\gleam__init__.py in ()
5 import os
6 import json
----> 7 import urlparse
8 from collections import namedtuple
9
ModuleNotFoundError: No module named 'urlparse'
I looked for the solution and I found that urlparse has been moved to a new module in python 3, which can be imported as
from urllib.parse import urlparse
And I even imported it, but still when I trying to import "gleam" package it shows error of module "urlparse". Can you suggest me how to bypass it (bypassing import urlparse statement and importing gleam package in Python 3).
I know how to import the urlparse but I don't know how to import the gleam package.
You have two possiblities:
Modify source code yourself as you stated inside gleam package, but it could work incorrectly.
Fall back to version of python it works on - so 2.7 it seems, since the modification you mentioned was done with python 3.0 release. It's stated in docs here.
Just do this to get over it:
from:
import urlparser
to:
import urllib.parse
I can't import anything from directories named "code".
I have the following directory structure:
In [1]: ls
code/ data/ pickles/
code_copy/ documentation/ submissions/
code_copy is an exact copy of code
In [2]: ls code_copy/
santander.py
__init__.py santander.pyc
In [3]: ls code
santander.py
__init__.py santander.pyc
However, the behavior of these two directories is different when I try to import something from them. For example, I can't import santander.py from code
In [4]: from code.
code.InteractiveConsole code.compile_command
code.InteractiveInterpreter code.interact
In [5]: from code import santander
---------------------------------------------------------------------------
ImportError Traceback (most recent call last)
<ipython-input-20-e36a94117eb8> in <module>()
----> 1 from code import santander
ImportError: cannot import name santander
while I'm able to do it from code_copy
In [6]: from code_copy.
code_copy.santander
In [7]: from code_copy import santander
In [8]:
Is this ipython's behavior normal? Is "code" a especial name? How can this be fixed?