Why does unittest.mock.patch work with testfixtures? - python-3.x

Why doesn't accessing unittest.mock.patch throw an attribute error when I import testfixtures in the below code?
I myself suspect that it is because testfixtures might be importing unittest.mock somewhere internally however, is there any way I could change this behavior if I want unittest.mock to always be imported explicitly and get an AttributeError otherwise?
import unittest
import sys
import os
import testfixtures
class Test(unittest.TestCase):
#unittest.mock.patch('sys.version_info', (2,7,0))
def test_version(self):
assert(sys.version_info < (3,0,0))
Accessing unitest.mock without importing it should throw an AttributeError but that's not the case when testfixtures is imported.

Related

How to suppress outputs from specific modules and hidden class methods in Python?

This is how the code looks like
#!/usr/bin/env python3
#encoding:utf-8
import requests, numpy, fasttext, os, sys
from itertools import product
from math import sqrt
en_model=fasttext.load_model(path='crawl-300d-2M-subword.bin')
The script is intended to train a classification model using some NLP techniques. Here is the problem.
The last line of the snippet, for some unknown reason, outputs an empty line to the stderr, even though it runs without error. Is there any way to suppress it from the calling module, or do I have to hack into the fasttext module to know which line is causing this? In general, is there any way to suppress any stdout or stderr echo within a code snippet, specifically when I know that they are caused by modules being imported rather than what I wrote?
You can check contextlib.redirect_stdout and contextlib.redirect_stderr
Sample:
from contextlib import redirect_stdout
from contextlib import redirect_stderr
import os
def cache_stdouterr(func):
def wrapper():
with open(os.devnull,"w") as f:
with redirect_stdout(f):
with redirect_stderr(f):
func()
return wrapper
#cache_stdouterr
def noprint():
print("notprinted")
def toprint():
print("shouldbeprinted")
toprint()
noprint()
# python3 test_redirect.py
shouldbeprinted
This is the generic solution. For your specific problem , you can try this :
#!/usr/bin/env python3
#encoding:utf-8
import requests, numpy, fasttext, os, sys
from contextlib import redirect_stdout, redirect_stderr
from itertools import product
from math import sqrt
with redirect_stderr(open(os.devnull,"w")):
en_model=fasttext.load_model(path='crawl-300d-2M-subword.bin')

Import an Error class from a package in python

How can I import the Error class (and only the error class, not a namespace) in python to be used in an exception handling?
What's not intended to be used:
from tkinter import _tkinter as tk
try:
...
except tk.TclError:
print('Oops. Bad window path.')
I've tried the above, which works but doing so also imports a bunch of other things into my namespace that I don't need and I also need to use tk.TclError to reference it instead of simply TclError.
What I try to avoid, since it imports the whole package that I do not need, I solely need to handle the exception:
import tkinter as tk
try:
...
except tk.TclError:
print('Oops. Bad window path.')
So how do I import the Error class alone from the package, without getting the whole tkinter namespace, if that's even possible or recommandable?
I have two seperate Programs, I'll call them A and B here to shorten it.
What I would like to achieve
A.py
## Communicator ##
import B
#... Some irrelevant code ...
GUI = B.start()
try:
#Tell the GUI to modify something, for example:
GUI.entry.insert(0, 'Input')
except TclError:
#Modification failed due to Bad Window Path
B.py
## GUI ##
import tkinter as tk
#Little Function to give the Communicator the required object to start/handle the GUI
def start():
root = tk.Tk()
run = Alarmviewer(root)
return run
#... GUI initialization, creating/destroying of windows, modifications, etc
The TclError class can be imported from tkinter. To make it available as tk.TclError just import tkinter with the name tk:
import tkinter as tk
try:
...
except tk.TclError:
...
You can, of course, import just the TclError exception if you wish, though it really doesn't have any actual advantage over importing the entire module in this particular example:
from tkinter import TclError
try:
...
except TclError:
...
Your question claims you must reference it as tk.TclError, but that is a false statement. You reference it by the name you import it as. The name is irrelevant, what is important is the actual exception object itself.
For example, create a file named gui.py, and in that file put this:
# gui.py
import tkinter as tk
def do_something():
raise tk.TclError("something bad happened")
Next, in another file add the following code:
from tkinter import TclError
import gui
try:
gui.do_something()
except TclError:
print("I caught the TclError")
When you run the code, you should see "I caught the TclError" printed.

Python Type is not defined

I want to do the semantic checking for a language and i use ANTLR4 to generate parser and visitor class. However i met a problem.
If i use this method print(type(newList[0].expression()))
I will get a type like this <class 'IDILParser.IDILParser.IdenetExpressionContext'>
However, if i run the code below, i will get a error like this NameError: name 'IDILParser' is not defined
Can i ask how to fix this problem? Thanks!
from antlr4 import *
if __name__ is not None and "." in __name__:
from .IDILParser import IDILParser
else:
from IDILParser import IDILParser
class IDILVisitor(ParseTreeVisitor):
def visitAssign(self, ctx:IDILParser.AssignContext):
if type(newList[0].expression()) is IDILParser.IDILParser.IdenetExpressionContext:
...
You did from IDILParser import IDILParser, which means the IDILParser in your code already acutally refers to IDILParser.IDILParser.
So try taking away that one layer:
if type(newList[0].expression()) is IDILParser.IdenetExpressionContext:
...
Btw, when in doubt if your code is being run as a module or as a script (aka relative imports do work or not), you could also do the following:
try:
from .IDILParser import IDILParser
except ImportError:
from IDILParser import IDILParser

python confusion on importing modules

I saw this statement
from django import forms
the folder structure is
django\
__init__.py
forms\
__init__.py
..(continues)
My doubt is instead of the above statement why cant we imports forms like this.
import django.forms
when i tried this in pycharm. it says unused import statement.
the following is my code:
#from django import forms
import django.forms
from .models import Post
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ('title', 'text',)
it gives me error
class PostForm(forms.ModelForm):
NameError: name 'forms' is not defined
From python's docs,
... when using syntax like import item.subitem.subsubitem, each item
except for the last must be a package; the last item can be a module
or a package but can’t be a class or function or variable defined in
the previous item.
Then since its __init__.py designates forms as a package, you should be able to import it via import django.forms. Accessing its members will be different since where before you wrote forms.x now you would write django.forms.x.

python 3 import urllib.request module

I am learning to grab pictures from URL and found a Q&A here. Since it's Python 3, I changed import urllib to import urllib.request and
urllib.urlretrieve("http://www.digimouth.com/news/media/2011/09/google-logo.jpg", "local-filename.jpg")
to
urllib.request.urlretrieve("http://www.digimouth.com/news/media/2011/09/google-logo.jpg", "local-filename.jpg").
It doesn't work! It says AttributeError: 'module' object has no attribute 'urlretrieve'
I then changed urllib.urlretrieve to def request.urlretrieve and got SyntaxError: invalid syntax
I also tried def urlretrieve and it's not working either.
Could anyone tell me how to get it right? Thanks!
What if the URL contains more than one pic?
You need to use:
from urllib import request
request.urlretrieve("http://www.digimouth.com/news/media/2011/09/google-logo.jpg", "local-filename.jpg")
You can use also use:
import urllib.request
urllib.request.urlretrieve("http://www.digimouth.com/news/media/2011/09/google-logo.jpg", "local-filename.jpg")
Since you have imported urllib.request module, doesn't it seem obvious that you should call its method urlretrieve(args) as urllib.request.urlretrieve(args).
When you type import <module>, you call its method using <module>.method(args) (As specified in above code).
Alternatively, you can import the module using from <module> import * and then call its method using method(args). Eg -
from urllib.request import *
urlretrieve(args).
Another way is to only import the method you need to use in your program using
from <module> import method and then call the method using method(args). Eg -
from urllib.request import urlretrieve and then call the method using
urlretrieve(args).
The urllib.request module for Python 3 is well documented here.

Resources