python spec works differently as mentioned in the documentation - python-3.x

>>> from mock import *
>>> from urllib import request
>>> mock = Mock(spec=request.Request)
>>> mock.has_data()
<mock.Mock object at 0x...>
>>> mock.has_data.assret_called_with()
From : https://docs.python.org/3/library/unittest.mock.html#autospeccing
1) How can the statement "mock.has_data()" work as it throws error on my system ?
I do not find has_data() mentod in the request library.
2) Assuming even if we have "has_data()", I doubt how the below call works and doesnt throw attirbute error ?
Eg: mock.has_data.assret_called_with()
In my case with below example it fails but above mentioned example in python documentation doesn't report any error
from mock import *
from urllib import request
mock = Mock(spec=request.Request)
mock.has_header()
mock.has_header.assret_called_with()
Traceback (most recent call last):
  File ".\test2.py", line 5, in <module>
    mock.has_header.assret_called_with()
  File "C:\Users\hai\AppData\Local\Programs\Python\Python35-32\lib\site-packages\mock\mock.py", line 703, in __getattr__
    raise AttributeError(name)
AttributeError: assret_called_with
Please clarify, Is something wrong with my understanding or wrong with the documentaion ?

The example in the documentation is outdated (it is a bug. You can help fixing it). It worked as described in Python 3.3. mock.has_data() should raise AttributeError in Python 3.4+:
Changed in version 3.4: The request methods add_data, has_data, get_data, get_type, get_host, get_selector, get_origin_req_host and is_unverifiable that were deprecated since 3.3 have been removed.
The documentation should use a method that exists on request.Request object (such as mock.has_header()). The point is to illustrate the difference between mock.nonexisting (raises AttributeError if request.Request has no such attribute) and mock.some_existing_attribute.some_nonexisting_attribute (the latter doesn't raise AttributeError even if mock.some_existing_attribute has no some_nonexisting_attribute attribute):
>>> from unittest.mock import Mock
>>> from urllib import request
>>> mock = Mock(spec=request.Request)
>>> mock.has_header() # there is request.Request.has_header
<Mock name='mock.has_header()' id='174952746'>
>>> mock.nonexisting # there is no request.Request.nonexisting
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/...python3.6/unittest/mock.py", line 582, in __getattr__
raise AttributeError("Mock object has no attribute %r" % name)
AttributeError: Mock object has no attribute 'nonexisting'
Mock object has no attribute 'nonexisting'
>>> mock.has_header.nonexisting # no exception but there is no has_header.nonexisting
<Mock name='mock.has_header.nonexisting' id='249631353'>
In other words, spec is not recursive.

Related

Class assignment: object not callable [duplicate]

As a starting developer in Python I've seen this error message many times appearing in my console but I don't fully understand what does it means.
Could anyone tell me, in a general way, what kind of action produces this error?
That error occurs when you try to call, with (), an object that is not callable.
A callable object can be a function or a class (that implements __call__ method). According to Python Docs:
object.__call__(self[, args...]): Called when the instance is “called” as a function
For example:
x = 1
print x()
x is not a callable object, but you are trying to call it as if it were it. This example produces the error:
TypeError: 'int' object is not callable
For better understaing of what is a callable object read this answer in another SO post.
The other answers detail the reason for the error. A possible cause (to check) may be your class has a variable and method with the same name, which you then call. Python accesses the variable as a callable - with ().
e.g. Class A defines self.a and self.a():
>>> class A:
... def __init__(self, val):
... self.a = val
... def a(self):
... return self.a
...
>>> my_a = A(12)
>>> val = my_a.a()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
>>>
The action occurs when you attempt to call an object which is not a function, as with (). For instance, this will produce the error:
>>> a = 5
>>> a()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
Class instances can also be called if they define a method __call__
One common mistake that causes this error is trying to look up a list or dictionary element, but using parentheses instead of square brackets, i.e. (0) instead of [0]
The exception is raised when you try to call not callable object. Callable objects are (functions, methods, objects with __call__)
>>> f = 1
>>> callable(f)
False
>>> f()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
I came across this error message through a silly mistake. A classic example of Python giving you plenty of room to make a fool of yourself. Observe:
class DOH(object):
def __init__(self, property=None):
self.property=property
def property():
return property
x = DOH(1)
print(x.property())
Results
$ python3 t.py
Traceback (most recent call last):
File "t.py", line 9, in <module>
print(x.property())
TypeError: 'int' object is not callable
The problem here of course is that the function is overwritten with a property.

Howto read odata into pandas with python

I'm trying to load odata into
This is my code:
import pandas as pd
import pyodata
import requests
SERVICE_URL = 'http://services.odata.org/V2/Northwind/Northwind.svc/'
HTTP_LIB = requests.Session()
northwind = pyodata.Client(SERVICE_URL, HTTP_LIB)
df = pd.DataFrame(northwind)
I get this error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\KrestenSkovstedBuch\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pandas\core\frame.py", line 730, in __init__
raise ValueError("DataFrame constructor not properly called!")
ValueError: DataFrame constructor not properly called!
I think I need something in between my pyodata object and my DataFrame.
What would that be?
It needs to be some your own code :)
You are passing northwind, which is Pyodata.Client class to DataFrame constructor, which, well, expects something else. You must query your odata service using pyodata and then use the returned data structure (JSON probably) to initialize the Pandas DataFrame correctly, this is a more generic and already answered problem.

Why 'int' object is not callable?

try:
from logging import getLogger, ERROR
getLogger('scapy.runtime').setLevel(ERROR)
from scapy.all import *
conf.verb(0)
except ImportError:
print("[!]failed to import scapy")
sys.exit(1)
Error:
Traceback (most recent call last):
File "/home/dontalion/Desktop/python-programming/untitled/test-mitm.py", line 10, in <module>
conf.verb(0)
TypeError: 'int' object is not callable
Do you perhaps mean to do conf.verb = 0? conf.verb is an integer, so you cannot call it like a function as you are doing with conf.verb(0). You can see this in the source code here.
There's also this Stack Overflow question about setting Scapy's verbosity to 0.

Utilizing collections module in Python 3

Relatively pointed question. Currently running Python 3.4.1 and am just working on an object-orientated exercise where I need to overwrite some functions from an inherited class.
Goal:
importing from builtin module collections and utilizing collections.UserList rewrite the append, extend so that it will not "add" any duplicates if detected. (this part accomplished)
Problem:
The main problem is that I still am learning object oriented programming and I want to build objects which can be easily typed in and returned so I am writing a str and repr for my class
Currently my class looks like the below: (omitted the "goal" stuff because it works)
import collections
class UList (collections.UserList):
def __init__(self, entry =[]):
self.entry = entry
def __str__ (self):
print (self.entry)
return
def __repr__(self):
return self.__str__()
Then I decide to run some sample code for good measure:
>>> x = UList ([4,5,6])
>>> x.entry
[4, 5, 6]
>>> x
[4, 5, 6]
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
x
TypeError: __repr__ returned non-string (type NoneType)
>>> print(x)
[4, 5, 6]
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
print(x)
TypeError: __str__ returned non-string (type NoneType)
usually I look straight to the objects and try to figure out what went wrong but I am a little confused as I am still new =(. Can someone help explain why it is returning a NoneType even after I have overwritten the init? (also, a possible solution on how I can rectify so no error would be extremely helpful)
Consider (note no explicit return at the end of __str__) :
>>> class Foo:
... def __str__(self):
... print('Foo!!')
...
>>> f=Foo()
>>> f
<__main__.Foo object at 0x10a655080>
>>> print(f)
Foo!!
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: __str__ returned non-string (type NoneType)
Vs:
>>> class Foo:
... def __str__(self):
... return 'Foo!!!'
...
>>> f=Foo()
>>> print(f)
Foo!!!
The issue is that __repr__ and __str__ need to return a return a string. The return from __repr__ should, if possible, be the 'official' string representation of the object for eval to recreate the object or some other <useful definition> according the the docs on __repr__
The docs on __str__ a more convenient or concise representation can be used' other than a Python expression.

AttributeError: 'module' object has no attribute 'urlretrieve'

I am trying to write a program that will download mp3's off of a website then join them together but whenever I try to download the files I get this error:
Traceback (most recent call last):
File "/home/tesla/PycharmProjects/OldSpice/Voicemail.py", line 214, in <module> main()
File "/home/tesla/PycharmProjects/OldSpice/Voicemail.py", line 209, in main getMp3s()
File "/home/tesla/PycharmProjects/OldSpice/Voicemail.py", line 134, in getMp3s
raw_mp3.add = urllib.urlretrieve("http://www-scf.usc.edu/~chiso/oldspice/m-b1-hello.mp3")
AttributeError: 'module' object has no attribute 'urlretrieve'
The line that is causing this problem is
raw_mp3.add = urllib.urlretrieve("http://www-scf.usc.edu/~chiso/oldspice/m-b1-hello.mp3")
As you're using Python 3, there is no urllib module anymore. It has been split into several modules.
This would be equivalent to urlretrieve:
import urllib.request
data = urllib.request.urlretrieve("http://...")
urlretrieve behaves exactly the same way as it did in Python 2.x, so it'll work just fine.
Basically:
urlretrieve saves the file to a temporary file and returns a tuple (filename, headers)
urlopen returns a Request object whose read method returns a bytestring containing the file contents
A Python 2+3 compatible solution is:
import sys
if sys.version_info[0] >= 3:
from urllib.request import urlretrieve
else:
# Not Python 3 - today, it is most likely to be Python 2
# But note that this might need an update when Python 4
# might be around one day
from urllib import urlretrieve
# Get file from URL like this:
urlretrieve("http://www-scf.usc.edu/~chiso/oldspice/m-b1-hello.mp3")
Suppose you have following lines of code
MyUrl = "www.google.com" #Your url goes here
urllib.urlretrieve(MyUrl)
If you are receiving following error message
AttributeError: module 'urllib' has no attribute 'urlretrieve'
Then you should try following code to fix the issue:
import urllib.request
MyUrl = "www.google.com" #Your url goes here
urllib.request.urlretrieve(MyUrl)

Resources