I have a response from a URL which is of this format.
'history': {'all': [[u'09 Aug', 1,5'],[u'16 Aug', 2, 6]]}
And code is :
response = urllib.urlopen(url)
data = json.loads(response.read())
print data["fixture_history"]['all']
customObject = MyObject (
history = data["history"]['all']
)
Printing works but in my custom class I am seeing this error :
history = data["history"]['all']
TypeError: 'module' object is not callable
My class is :
class MyObject:
#init
def _init_(self,history):
self.hstory = history
Printing works but in my custom class I am seeing this error :
TypeError: 'module' object is not callable
I bet your your class is defined in a module named MyObject.py and that you imported it as import MyObject instead of from MyObject import MyObject, so in your calling code, name MyObject is bound to the module, not the class.
If you Class is defined in a different Module please make sure that that you have imported it the right way ie. you need to use from X import Y format but not Import X and expect it to work as if we do it that way we need to let python know the module we are calling it from.
And i am not very sure but i think the typo in the constructor might case the issue as stated
bigOTHER
Related
I have a strange problem and I can't seem to find a solution. I'm creating a Python app that sends a get request to an endpoint, fetches some data in JSON format and processes it to insert it into a database later. I have to classes, one is like APIClient, and the other is just a namespace to hold some methods to transform the data, let's call it APITransform.
There is a problematic method in APITransform, so here's the code.
#api.py module"
class APITransform:
...
#staticmethod
def flatten(data:dict, method:str):
if method == "some flattening method from a config file":
return list(data.values())
....
class APIClient:
....
def get_data():
....
response = requests.get(URL, headers, params)
json_resp = response.json()
json_resp = APITransform.flatten(
json_resp, "some flattening method from a config file")
#main.py module
from api import APIClient
api_client = APIClient()
api_client.get_data()
The error traces to APITransform.flatten() with the message:
return list(data.values())
AttributeError: 'list' object has no attribute 'values'
EDIT: The strange thing is that If I print the type of json_resp object before passing it to APITransform.flatten() in get_data(), I get two outputs in two lines: <class dict> and <class list>. It's like get_data() is being called twice, but I searched it in the entire project, I can only find it in two places, the definition in APIClient and call in main.py. I'm out of debugging ideas.
Anyone with an idea? Thanks
the code can raise such an error if the result of the json which is returned from a server, is a list, for example, if the response (from the server) is something like "[1,2,3]" or any other json list, the json_resp variable would be a list, that of course has no values() function. make sure the server returns the data in proper format or use an if statement to check before passing to the flatten function.
I have module with name Ioanv1:
...
person1={"temp_lags": [-21.96,-21.82,-21.89,-21.99]}
...
def ....
Now I want to replace person1 with new data in another script:
import json
import Ioanv1
person1={"temp_lags": [-21,-21,-21,-21]}
jsonToPython = Ioanv1(person1)
print(jsonToPython)
I get TypeError: 'module' object is not callable
Could you please help me.
Error message is simple and clear.
Ioanv1 is module
You are using Ioanv1(person1) which you can not.
You probably want something like: Ioanv1.person1
I'm using Google Places API code to get the places and its details so in that code I want to pass variable name instead of its attribute type
Here is the snippet
WORKS FINE
query_result = google_places.nearby_search(
location='London, England', keyword='Fish and Chips',
radius=20000, types=[types.TYPE_FOOD])
GIVES ERROR
place_type='TYPE_FOOD'
query_result = google_places.nearby_search(
location='London, England', keyword='Fish and Chips',
radius=20000, types=[types.place_type])
AttributeError: module 'googleplaces.types' has no attribute 'place_type'
Any suggestion on how can it be done?
Thanks
Domnick
You can use getattr
1) If TYPE_FOOD is a property you can use:
getattr(types, place_type)
2) If TYPE_FOOD is a method, you should call it:
getattr(types, place_type)()
Note: I am assuming that your method takes no arguments.
How can I deserialize a protocol buffer message, knowing only the string name of the protoc-generated class?
For some reason, the fully qualified name of the message that I get with DESCRIPTOR.full_name does not match the actual location of the python class, so I am unable to deserialize it with the following function:
def get_class( kls ):
"""Get class given a fully qualified name of a class"""
parts = kls.split('.')
module = ".".join(parts[:-1])
m = __import__( module )
for comp in parts[1:]:
m = getattr(m, comp)
return m
I just get ImportError no module (name).
Any help appreciated.
P.S.: In case it helps, the bigger problem I am trying to solve is to serialize the protobuf message to the database, and then deserialize it back out (I am using postgresql with sqlalchemy in this case). Since regular python pickle doesn't work - I am hoping to store a tuple (message_cls_name, message_binary) where message_cls_name is a fully qualified name of the protobuf message, and message_binary is a result of called SerializeToString on the message. The part I am not clear about is how to get the message out and deserialize it into proper protobuf class.
Here is an example solution..
from ocmg_common.protobuf.rpc_pb2 import Exception as PBException
from importlib import import_module
pb_message = PBException(message='hello world')
pb_message_string = pb_message.SerializeToString()
def deserialize(message, typ):
module_, class_ = typ.rsplit('.', 1)
class_ = getattr(import_module(module_), class_)
rv = class_()
rv.ParseFromString(message)
return rv
print(deserialize(pb_message_string, 'ocmg_common.protobuf.rpc_pb2.Exception'))
will output
(env)➜ httppost git:(master) ✗ python test.py
message: "hello world"
If you dont know the module, but only have the DESCRIPTOR.full_name you have to name them the same way, or create a function that maps a full descriptor name to a module. Otherwise you are stuck and dont know from where to import the module.
I hope it will help you.. ;)
Best of luck..
I'm having difficuly getting my head around python's mock test methodology.
I want to do some mocking on this file.
Since packages xbmc, xbmcaddon and xbmcgui cannot be imported in a normal python environment I've managed to mock them out like this:
class XBMCTestCase(unittest.TestCase):
def setUp(self):
#Mock up any calls to modules that cannot be imported
self.xbmc = Mock()
self.xbmcgui = Mock()
self.xbmcaddon = Mock()
modules = {
'xbmc' : self.xbmc,
'xbmcgui': self.xbmcgui,
'xbmcaddon': self.xbmcaddon
}
self.module_patcher = patch.dict('sys.modules', modules) ##UndefinedVariable
self.module_patcher.start()
See it in action here.
So when I import setlocation.py I get an error like this:
File "/home/paulo/workspace/weather.metoffice/src/metoffice/utils/utilities.py", line 21, in <module>
CACHE_FOLDER = os.path.join(ADDON_DATA_PATH, 'cache')
File "/usr/lib/python2.7/posixpath.py", line 78, in join
path += b
TypeError: unsupported operand type(s) for +=: 'Mock' and 'str'
Even if I mock out 'metoffice.utils' (by adding it to the list of modules in the patch created at setup) I get a similar error in setlocation.py
File "/home/paulo/workspace/weather.metoffice/src/metoffice/setlocation.py", line 32, in <module>
GEOIP_PROVIDER = int(__addon__.getSetting('GeoIPProvider'))
TypeError: int() argument must be a string or a number, not 'Mock'
So I need __addon__.getSetting() to return a string.
Any ideas?
All attempts have failed, but I don't think I have a full grasp of the capabilities of the mock package.
Note I'm on Python 2.7.3 with mock 1.0.1
You need to tell your mocks what to return. The __addon__ value is the result of a xbmcaddon.Addon() call, so you can get access to that mock object with:
addon = self.xbmcaddon.Addon.return_value
because .return_value gives you the actual Mock object that calling Addon() would return.
Now you can tell that Mock object what to return when the getSetting() method is called; there are two values to provide here, so you could use the side_effect to set a sequence of values to return:
addon.getSetting.side_effect = ['some_api_key', '42']
where the first call to __addon__.getSetting() will produce the first value 'some_api_key', the second cal will produce '42'.