I have an object self.config which has some variables, I would like to first check if a variable ('db_password') exist in self.config and if it exists then modify the variable value something like self.config.db_password = 'modified values' . following is the python code
if hasattr(self.config, enc_variable):
setattr(self.config, enc_variable, f.decrypt(self.config.enc_variable.encode('ascii')).decode('ascii'))
AttributeError: 'Config' object has no attribute 'enc_variable'
This part is buggy:
self.config.enc_variable
It should be
getattr(self.config, enc_variable)
Or
self.config.db_password
Related
I am enumerating some objects in a list, which may or may not have certain properties. If a property does not exists, I get the AttributeError. What I want to do is to catch the exception object and retrieve the specific property that causes the error and set it to an empty string. I don't see any method in the AttributeError object to retrieve the said attribute.
Partial code here:
import wmi
c = wmi.WMI ()
for account in c.Win32_Account():
try:
print(f"Name: {account.Name}, FullName: {account.FullName}, LocalAccount: {account.LocalAccount}, Domain: {account.Domain}")
except AttributeError as error:
# How do I retreive the attribute in question from the exception object?
Per original post, you want to "retrieve the specific property that causes the error and set it to an empty string".
if you just wanted to print the string use getattr:
https://docs.python.org/3/library/functions.html#getattr
import wmi
c = wmi.WMI ()
for account in c.Win32_Account():
print(f"Name: {getattr(account, 'Name', "")}, FullName: {getattr(account, 'FullName', "")}, LocalAccount: {getattr(account, 'LocalAccount', "")}, Domain: {getattr(account, 'Domain', "")}")
if you want to actually overwrite the missing values use hasattr and setattr:
for account in c.Win32_Account():
for attr in ['Name', 'FullName', 'LocalAccount', 'Domain']:
if not hasattr(account, attr):
setattr(account, attr, "")
Every Exception object stores its arguments in the .args property. The argument to an AttributeError object is a string that contains the object on which the property access is being used and the property being accessed.
The format of this message looks like-
('|")object_name('|") object has no attribute ('|")property_name('|")
Where ('|") means "either matching double quotes or single quotes"
You can extract both the object name and property name using this regex-
(?:\'|")(\w+)(?:\'|")
So the final implementation would look like-
import wmi
import re
c = wmi.WMI ()
for account in c.Win32_Account():
try:
print(f"Name: {account.Name}, FullName: {account.FullName}, LocalAccount: {account.LocalAccount}, Domain: {account.Domain}")
except AttributeError as error:
property_name = re.findall(r'(?:\'|")(\w+)(?:\'|")', error.args[0])[-1]
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
This is my function:
def get_content(self):
full_results = []
for res in self._get_data(): #function that returns suds object
final_dict = dict(res)
final_dict.pop('readOnlyContactData', None)
if res["readOnlyContactData"] is not None:
readOnlyContactData_dict = dict(res["readOnlyContactData"])
final_dict.update(readOnlyContactData_dict)
full_results.append(final_dict)
return full_results
However when runnning it I get:
INFO - if res["readOnlyContactData"] is not None:
INFO - File "/home/ubuntu/.local/lib/python3.6/site-packages/suds/sudsobject.py", line 154, in __getitem__
INFO - return getattr(self, name)
INFO - AttributeError: 'contactObject' object has no attribute 'readOnlyContactData'
INFO - Command exited with return code 1
I don't understand why it fails the if condition is suppose to check if res["readOnlyContactData"] exists. if it does process it and if not ignore it.
Why this condition fails?
In python, using variable['key'] syntax internally calls __getitem__('key') to retrieve the right element. In your case, the error indicates that __getitem__() internally calls getattr(), which is usually used to retrieve a class member or an instance variable.
File "/path/to/sudsobject.py", line 154, in __getitem__
return getattr(self, name)
AttributeError: 'contactObject' object has no attribute 'readOnlyContactData'
So, based on information you provided, calling res["readOnlyContactData"] seems equivalent to call res.readOnlyContactData. Since readOnlyContactData attribute is not found in your object (of type contactObject), you get this error.
Try the following statements to check wether your object has the member you are looking for or not:
>>> # this has to be implemented in your class
>>> "readOnlyContactData" in res
or
>>> hasattr(res, "readOnlyContactData")
That if condition checks whether the element residing in res["readOnlyContactData"] is None or not. So, if res does not have any index named "readOnlyContactData" Python returns the exception Object has no attribute. Instead of the if-statement you should try hasattr(res, "readOnlyContactData")
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
I'm new to python. I'm trying to unzip a file in my current script directory but I can't get this work...
zip = zipfile.ZipFile(os.getcwd() + '/Sample_APE_File.zip')
zip.extractall(os.getcwd())
Error: AttributeError: 'str' object has no attribute 'getcwd'
You assigned a string value to os, it is no longer bound to the module:
os = 'some string'
Rename that to something else.