I have a dictionary (dict1)
dict1={
'lala':{
'name':'lala',
'lula':0xcafecafe,
},
'mene':{
'name':'mene',
'lula':0xdeadbeef,
},}
After that i created a register class to parse in the information
class register:
def __init__(self,name):
self.name = dict1[name].get('name')
self.data = dict1[name].get('lula')
def self_add(self):
value = self.data + self.data
print('self_add value : {}'.format(value))
and create a for loop to populate the it
for name, info in dict1.items():
reg_class = register(name)
vars()[reg_class.name]=reg_class ##work
vars()['base_path'+'.'+reg_class.name]= reg_class ## not working
however, when i use vars()[reg_class.name]=reg_class it is working
>>> mene.data
3735928559
>>> hex(mene.data)
'0xdeadbeef'
but when i use vars()['base_path'+'.'+reg_class.name]= reg_class it is not working
>>> base_path.mene.data
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'base_path' is not defined
How can i do that correctly?
Related
Im trying to load the data from a list in python where, I save the data in a list:
class Region(object):
def __init__(self, cities: list[CitiySalah], label: str):
self.cities = cities
self.label = label
def toMap(self) -> dict:
map = self.__dict__
r = [{}]
for x in self.cities:
r.append(x.toMap())
map["cities"] = r
return map
and the one that loads the data is:
def startLoading() -> list[Region]:
.......
for select in selects:
if select.has_attr("name") and select['name'] == "ville":
groups = select.find_all('optgroup')
for group in groups:
lable = group['label']
allR = {"lable": lable}
cities = [CitiySalah]
for option in group:
try:
# the city
if(option.has_attr('value')):
value = option['value']
city = str(option).split('<')[1].split('>')[1]
id = str(option).split('<')[1].split(
'?ville=')[1].split('"')[0]
dataUrl = url+"?ville="+id
data = MySalah(getSalahHour(dataUrl))
R = CitiySalah(argu={"value": value,
"city": city,
"dataUrl": dataUrl,
"id": id, }, data=data)
# print(R.toMap())
cities.append(R)
except:
pass
# allR['cities'] = cities
res.append(Region(label=lable, cities=cities))
return res
and when I'm trying to call the function by:
def getDataForDatabase():
listR = [{}]
data = startLoading()
for x in data:
listR.append(x.toMap())
return listR
I get this error
Traceback (most recent call last):
File "/home/nimr/ServerApps/ScrappingProject/Salah/Functions.py", line 108, in <module>
print(getDataForDatabase())
File "/home/nimr/ServerApps/ScrappingProject/Salah/Functions.py", line 104, in getDataForDatabase
listR.append(x.toMap())
TypeError: toMap() missing 1 required positional argument: 'self'
I have tried, I'm still new in python as I'm from c++ family, and I got stuck here,
I need to save the data in a list and convert them into Map, so I can save them in the database (NoSQL).
and as for the rest of models they are working correct, I don't know why I'm getting this error.
I am using the shelve module to save some Python objects (strings in the example).
When I am trying to save an object as a nested key, then it is not being saved.
class Car:
def __init__(self, ID):
self.id = ID
def save_to_shelf(self):
with shelve.open('shelf') as shelf:
if not shelf.get('users'):
shelf['users'] = {}
print(shelf['users'])
try:
shelf['users'][self.id] = "hello"
except Exception as e:
print(e)
print('saved')
print(shelf['users'])
car = Car(123)
car.save_to_shelf()
The code should print:
{}
saved
{123: hello}
But instead it prints:
{}
saved
{}
Meaning that it is not getting saved
If I print the value of the key, it gives KeyError
shelf['users'][self.id] = "hello"
print(shelf['users'][self.id])
Error
Traceback (most recent call last):
File "P:/Python practice/Shelll/main.py", line 3, in <module>
car.save_to_shelf()
File "P:/Python practice/Shelll\db.py", line 20, in save_to_shelf
print(shelf['users'][self.id])
KeyError: '123'
I am able to save it if I do the following while saving
Instead of
with shelve.open('shelf') as shelf:
shelf['users'][self.id] = "hello"
This works
with shelve.open('shelf') as shelf:
USERS = shelf['users']
USERS[self.id] = self.id
shelf['users'] = USERS
# or this works
# with shelve.open('shelf') as shelf:
# shelf['users'] = {self.id:"hello"}
I want to understand the reason behind this. As far as I know, shelve objects work as a dictionary. So the way I was saving earlier should work but does not.
I have a class that takes an arbitrary HTML template and str.format()s it for a specific use case. For instance:
<h1>Hi, {userName}!</h1>
<p> It's {weather} today.</p>
would become:
<h1>Hi, Jon Skeet!</h1>
<p>It's sunny today.</p>
To do this, I have a Template class:
class Template:
def __init__(self, name, **kwargs):
templateDirectory = getTemplateDirectory() # we don't need to worry about this
with open(os.path.join(templateDirectory, "templates", name + ".html")) as templateFile: # we get the template we need
self.template = templateFile.read()
print(self.template) # all in order: we get the un-formatted HTML
print(kwargs) # all in order: we get a dict of things to replace (i.e. {'userName': 'Jon Skeet', 'weather': 'sunny'} )
self.final = self.template.format(**kwargs) # this should just replace things nicely, but it doesn't: why?
def __str__(self):
return self.final
I instantiate like this:
ErrorTemplate = Template('foo', var1=42, var2='foo')
print(str(ErrorTemplate))
The error I get is as follows:
Traceback (most recent call last):
File "/path/to/file.py", line 11, in <module>
ErrorTemplate = Template('foo', var1=42, var2='bar')
File "/path/to/the/file/with/Template/class.py", line 10, in __init__
self.final = self.template.format(**kwargs)
KeyError: 'document'
I'm not using 'document' anywhere. I have no idea where it gets 'document' from. What am I doing wrong?
I am trying to read key-value pairs from an already existing shelf to create a new class object with a updated field and write that class object to a new shelf.
My class object : SongDetails
This is the procedure which fails:
def updateShelfWithTabBody(shelfFileName, newShelfFileName):
"""this function updates songDetails with
html body i.e. just the part that contains lyrics and
chords in the tab """
#read all songDetails
shelf = shelve.open(shelfFileName)
listOfKeys = shelf.keys()
#create new songDetails object
temporaryShelfObject = SongDetails.SongDetails()
#iterate over list of keys
for key in listOfKeys:
#print "name:"+shelf[key].name
#fill details from temporaryShelfObject
temporaryShelfObject.name = shelf[key].name
temporaryShelfObject.tabHtmlPageContent = shelf[key].tabHtmlPageContent
#add new detail information
htmlPageContent = shelf[key].tabHtmlPageContent
temporaryShelfObject.htmlBodyContent = extractDataFromDocument.fetchTabBody(htmlPageContent)
#write SongDetails back to shelf
writeSongDetails.writeSongDetails(temporaryShelfObject, newShelfFileName)
Definitions for functions used in above code:
def fetchTabBody(page_contents):
soup = BeautifulSoup(page_contents)
HtmlBody = ""
try:
#The lyrics and chords of song are contained in div with id = "cont"
#Note: This assumtption is specific to ultimate-guitar.com
HtmlBody = soup.html.body.find("div",{"id":"cont"})
except:
print "Error: ",sys.exc_info()[0]
return HtmlBody
def writeSongDetails(songDetails, shelfFileName):
shelf = shelve.open(shelfFileName)
songDetails.name = str(songDetails.name).strip(' ')
shelf[songDetails.name] = songDetails
shelf.close()
SongDetails class:
class SongDetails:
name = ""
tabHtmlPageContent = ""
genre = ""
year = ""
artist = ""
chordsAndLyrics = ""
htmlBodyContent = ""
scale = ""
chordsUsed = []
This is the error that I get:
Traceback (most recent call last):
File "/l/nx/user/ndhande/Independent_Study_Project_Git/Crawler/updateSongDetailsShelfWithNewAttributes.py", line 69, in <module>
updateShelfWithTabBody(shelfFileName, newShelfFileName)
File "/l/nx/user/ndhande/Independent_Study_Project_Git/Crawler/updateSongDetailsShelfWithNewAttributes.py", line 38, in updateShelfWithTabBody
writeSongDetails.writeSongDetails(temporaryShelfObject, newShelfFileName)
File "/home/nx/user/ndhande/Independent_Study_Project_Git/Crawler/writeSongDetails.py", line 7, in writeSongDetails
shelf[songDetails.name] = songDetails
File "/usr/lib64/python2.6/shelve.py", line 132, in __setitem__
p.dump(value)
File "/usr/lib64/python2.6/copy_reg.py", line 71, in _reduce_ex
state = base(self)
File "/u/ndhande/.local/lib/python2.6/site-packages/BeautifulSoup.py", line 476, in __unicode__
return str(self).decode(DEFAULT_OUTPUT_ENCODING)
**RuntimeError: maximum recursion depth exceeded**
I couldn't find any reason why I'm getting this error even though there is no explicit recursive call in my code. I have seen this error in other stackoverflow posts, but they did have recursive calls in their case.
str(self) calls __str__ or calls __unicode__ calls str(self).
I keep getting an error when trying to run the rmakeprofile command. I get an error saying that 'type' object has no attribute '__getitem__'.
from array import array
from ROOT import gROOT, TCanvas, TProfile, TGraph
class Data(object):
def __init__(self, s):
self.p = TProfile()
self.data = []
for line in s:
if not line.startswith("#"): #Removes Commented lines
columns = line.split(',') #Splits into Columns
if columns:
datum = {
"threshold" : float(columns[1]),
"count" : float(columns[2]),
"rate" : float(columns[2]) /float(columns[0]),
"scantime" : float(columns[0])
}
self.data.append(datum)
print columns[1], float(columns[2])/float(columns[0])
def rmakeprofile(self, data, xval, yval, noBins):
self.a = array('d')
for datum in data:
self.a.append(float(datum[xval]))
self.p = TProfile('p','',noBins,min(self.a),max(self.a))
for datum in data:
self.p.Fill(datum[xval],datum[yval])
return self.p
Here is the traceback:
p = d.rmakeprofile(data,"threshold","rate",13)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "ray.py", line 27, in rmakeprofile
self.a = array('d')
TypeError: 'type' object has no attribute '__getitem__'
Try using the following replacements.
import numpy as np
self.a = np.asarray(['d'])
or even this also works
import numpy as np
self.a = np.asarray('d')