Convert string to property - AttributeError: can't set attribute - python

I was running python code below:
def dict2struct(d):
res = namedtuple("config", d.keys())(*d.values())
return res
cfg = {'fieldx': 'Allan', "fieldy": 45, 'fieldt': {'head': False, 'number': 2}}
res = dict2struct(cfg)
print(res)
res.fieldx = "Jack"
and got the error:
config(fieldx='Allan', fieldy=45, fieldt={'head': False, 'number': 2})
Traceback (most recent call last):
File "*****\Testings\test_x.py", line 97, in <module>
res.fieldx = "Jack"
AttributeError: can't set attribute
I have read the questions below and understand that it was because namedtuples are immutable and the property setter was restricted.
AttributeError: can't set attribute
AttributeError: can't set attribute in python
However, I need to convert a lot of strings from a configurational dictionary's keys to properties of a struct or a class. These strings values are not fixed as they are many.
Is there a way to get around of this AttributeError for my problem?

Steve's solution above worked for me.
pypi.org/project/attributedict

Related

TypeError: 'NoneType' object is not subscriptable in a int object

Here is a function to check the data and update it
div , update are my mongodb collection object
def data_updater(user1_id,code):
device_id = dvi.find_one({"user_id":user1_id},{"_id":0,"user_id":0})["device_id"]
prv_data = update.find_one({"device_id":device_id},{"_id":0,"device_id":0})
prv_date = prv_data["date"]
msg = prv_data["message"]
if prv_date < current_date and msg != code:
x = update.find_one_and_update({"device_id":id,},{"$set":message":code,"date":current_date}})
print(x.acknowledged)
and when I am calling the function it is giving TypeError data_updater(95626,972681)
the error
Traceback (most recent call last):
File line 170, in <module>
data_updater(95626,972681)
File line 71, in data_updater
device_id = dvi.find_one({"user_id":int(user1_id)},{"_id":0,"user_id":0})["device_id"]
TypeError: 'NoneType' object is not subscriptable
I am not able to find any mistake please help
Your context isn't very clear, however, from the error trace as generated it seems that your find_one() function returns None with the arguments as passed and you are trying to access the value for the key device_id. I recommend you refactor your find_one() function or make use of the following code to resolve the issue at hand:
def data_updater(user1_id,code):
try:
device_id = dvi.find_one({"user_id":user1_id},{"_id":0,"user_id":0})["device_id"]
prv_data = update.find_one({"device_id":device_id},{"_id":0,"device_id":0})
prv_date = prv_data["date"]
msg = prv_data["message"]
if prv_date < current_date and msg != code:
x = update.find_one_and_update({"device_id":id,},{"message":code,"date":current_date}})
print(x.acknowledged)
except TypeError:
print('No value found for specified parameters :/')
PS: I also didn't understand the use of $ in your code, so I removed it thinking of it as a mistake. Hope this helps! 😊

How to solve "AttributeError: 'NoneType' object has no attribute 'to_json'" problem?

I got "AttributeError: 'NoneType' object has no attribute 'to_json'" when I tried to make a function that would give output in JSON file using Jupyter notebook.
Here the code:
import json
def ma2(request):
request_json=json.loads(request)
nf=main_stat.func(request_json['variable1'],request_json['variable2'],request_json['variable3'])
return nf.to_json(orient="records")
the output:
AttributeError
Traceback (most recent call last)
<ipython-input-3-75b494d5499e> in <module>
9 "variable3":"Chemicals"}
10 request=json.dumps(k)
11 print(main(request))
<ipython-input-3-75b494d5499e> in ma2(request)
3 request_json=json.loads(request)
4 nf=main_stat.func(request_json['variable1'],request_json['variable2'],request_json['variable3'])
5 return nf.to_json(orient="records")
6
AttributeError: 'NoneType' object has no attribute 'to_json'
You didn't mention main_stat class but as i can see func function at main_stat class returns None, that doesn't have to_json function.
Check if statements that returns None value. or if you mean it your code could have empty json you must check nt value if it's not None then use to_json function.
import json
def ma2(request):
request_json=json.loads(request)
nf=main_stat.func(request_json['variable1'],request_json['variable2'],request_json['variable3'])
return nf.to_json(orient="records") if nt else {}

"str = str.replace("something", "something_else")" not working in Python 3.6.5

When I enter the following:
str = str.replace("something", "something_else")
It returns with:
AttributeError: 'tuple' object has no attribute 'replace'
I am on Python 3.6.5. Any help would be appreciated.
Check the content of str. It contains a tuple, not a string. Is it the output from a .split() operation or suchlike?
For example:
>>> str = ( 'a', 'b', 'banana' )
>>> str.replace("something", "something_else")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'tuple' object has no attribute 'replace'
Obviously it does work with the correct str:
>>> str = 'banana'
>>> str.replace("something", "something_else")
>>>

type object not subscriptable - python

from newsapi.sources import Sources
import json
api_key ='*******************'
s = Sources(API_KEY=api_key)
they input the category of news they want
wanted = input('> ')
source_list = s.get(category=wanted, language='en')
index = 0
sources = []
getting the sources
for source in source_list["sources"]:
data = json.dumps(source_list)
data = json.loads(data)
source = (data["sources"][index]["url"])
sources.append(source)
index += 1
from newspaper import Article
i = len(sources) - 1
looping through the source list and printing the articles
for source in sources:
url_ = sources[i]
a = Article[url_]
print(a)
i -= 1
getting error 'type' object is not subscriptable on the line a = Article[url_] have researched but still do not understand why in my case.
The simple solution to your problem is that the line:
a = Article[url_]
Should be:
a = Article(url_)
Now to get to why you're getting the TypeError: 'type' object is not subscriptable error.
This TypeError is the one thrown by python when you use the square bracket notation object[key] where an object doesn't define the __getitem__ method. So for instance, using [] on an object throws:
>>> object()["foo"]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'object' object is not subscriptable
In this case []s were used accidentally instead of ()s when trying to instantiate a class. Most classes (including this Article class) are instances of the type class, so trying object["foo"] causes the same error you are experiencing:
>>> object["foo"]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'type' object is not subscriptable

Problems with setdefault and Integers

I'm testing the following function:
def getDataMapOfFirstLine(line):
datamap = {}
for item in line:
hierarchy = item.split('^')
partialmap = datamap
i=0
for node in hierarchy:
partialmap = partialmap.setdefault(node, i)
i += 1
return datamap
It should create a dictionary out of the first line of a csv-file, that looks like this:
nummer;such;ans;bverb^konum;bverb^namebspr;bverb^bank^iident;
1213;HANS;Hans Dominik;111000222;Hans' account; DE2145432523534232;
1444555;DIRK;Dirk Daniel;13300002;Dirk's account; DE2134634565462352;
As you see these circumflex-signs in each semicolon-separated string are something like a join in SQL. If I execute it, I get this error:
Traceback (most recent call last):
File "./importtool.py", line 173, in <module>
main()
File "./importtool.py", line 38, in main
analyseImportFile(importfile, parser, options)
File "./importtool.py", line 119, in analyseImportFile
datamap = getDataMapOfFirstLine(line)
File "./importtool.py", line 149, in getDataMapOfFirstLine
partialmap = partialmap.setdefault(node, i)
AttributeError: 'int' object has no attribute 'setdefault'
If I replace the i in the setdefault-function by {} I get no error:
{'bverb': {'namebspr': {}, 'konum': {}, 'bank': {'iident': {}}}, 'such': {}, 'ans': {}}
This is nearly, what I want, but instead of the {} I would like to get a column-number.
I just don't get what is wrong. I tried this in interactive mode:
>>> mydict = {'foo': "Hallo", 'bar': 5}
>>> mydict.setdefault("sth", 12)
12
>>> print mydict
{'sth': 12, 'foo': 'Hallo', 'bar': 5}
As you see, this works...
I appreciate every help. Thanks in advance!
Your problem is this line:
partialmap = partialmap.setdefault(node, i)
dict.setdefault returns the thing that was set (or what was already there). In this case, it's an integer so you're setting partialmap to an int. You can probably just not grab the return value (which is what you've done in the interactive terminal BTW):
partialmap.setdefault(node, i)

Categories