Python - working with dictionaries - error - python

Link: https://www.w3schools.com/python/trypython.asp?filename=demo_ref_dictionary_update
def read_wpl_file(self,start,filename):
self.tree = ET.parse(filename)
self.smil = self.tree.getroot()
self.head = self.smil.find("head")
self.title = self.head.find("title").text
self.body = self.smil.find("body")
self.seq = self.body.find("seq")
self.media = self.seq.findall("media")
self.songs = []
for song_in_playlist in self.media:
self.song = {}
self.song.update({"path": song_in_playlist.attrib("src")})
self.song.update({"album_title" : song_in_playlist.attrib("albumTitle")})
self.song.update({"album_artist" : song_in_playlist.attrib("albumArtist")})
self.song.update({"title" : song_in_playlist.attrib("trackTitle")})
self.song.update({"artist" : song_in_playlist.attrib("trackArtist")})
self.song.update({"duration" : song_in_playlist.attrib("duration")})
self.songs.append(self.song)
print(self.songs)
self.song.update({"path": song_in_playlist.attrib("src")})
TypeError: 'dict' object is not callable

The error "object is not callable" means that the object in question does not support the function call syntax (e.g. attrib("src")).
xml.etree.ElementTree.Element.attrib is a dict, so you have to use the bracket syntax (attrib["src"]) or other dict methods to access its elements.
def read_wpl_file(self,start,filename):
self.tree = ET.parse(filename)
self.smil = self.tree.getroot()
self.head = self.smil.find("head")
self.title = self.head.find("title").text
self.body = self.smil.find("body")
self.seq = self.body.find("seq")
self.media = self.seq.findall("media")
self.songs = []
for song_in_playlist in self.media:
self.song = {}
self.song.update({"path": song_in_playlist.attrib["src"]})
self.song.update({"album_title" : song_in_playlist.attrib["albumTitle"]})
self.song.update({"album_artist" : song_in_playlist.attrib["albumArtist"]})
self.song.update({"title" : song_in_playlist.attrib["trackTitle"]})
self.song.update({"artist" : song_in_playlist.attrib["trackArtist"]})
self.song.update({"duration" : song_in_playlist.attrib["duration"]})
self.songs.append(self.song)
print(self.songs)

Related

insg1 = Insegnante.from_string(iron_man, "Ingegneria") AttributeError: type object 'Insegnante' has no attribute 'from_string'

I have this code:
class Insegnante(Persona):
profilo = "Insegnante"
def __init__(self, nome, cognome, età, residenza, materie=None):
super().__init__(nome, cognome, età, residenza)
if materie is None:
self.materie = []
else:
self.materie = materie
def scheda_personale(self):
scheda = f"""
Profilo: {Insegnante.profilo}
Materie: {self.materie}"""
return super().scheda_personale() + scheda
def aggiungi_materia(self,nuova):
if nuova not in self.materie:
self.materie.append(nuova)
print("Elenco materie aggiornato")
When I try to use it like so:
insg1 = Insegnante.from_string(iron_man, "Ingegneria")
I get this error:
insg1 = Insegnante.from_string(iron_man, "Ingegneria")
AttributeError: type object 'Insegnante' has no attribute 'from_string'
What is wrong with the code? How can I fix it?
You are trying to call the from_string method of the Insegnante class, but this class has no method from_string.
you can implement it yourself:
class Insegnante(Persona):
profilo = "Insegnante"
def __init__(self, nome, cognome, età, residenza, materie=None):
super().__init__(nome, cognome, età, residenza)
if materie is None:
self.materie = []
else:
self.materie = materie
def scheda_personale(self):
scheda = f"""
Profilo: {Insegnante.profilo}
Materie: {self.materie}"""
return super().scheda_personale() + scheda
def aggiungi_materia(self,nuova):
if nuova not in self.materie:
self.materie.append(nuova)
print("Elenco materie aggiornato")
def from_string(param1, param2):
# build your Insegante object and return it
return ...

Generating an add() function to a system created with a Linked List

I'm trying to make a phone book using Linked List.
I get the following error when I start printList function after adding new data with the add() function.
AttributeError: 'LinkedList' object has no attribute 'data'.
My printList function works before I add() something .
class Record:
def __init__(self, name, number):
self.name = name
self.number = number
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
r1 = Record(name="selman", number="541")
r2 = Record(name="mustafa", number="542")
r3 = Record(name="fatih", number="543")
r1_node = Node(data=r1)
r2_node = Node(data=r2)
r3_node = Node(data=r3)
phone_book = LinkedList()
phone_book.head = r1_node
r1_node.next = r2_node
r2_node.next = r3_node
def printList():
temp = phone_book.head
while temp:
print(f"name: {temp.data.name} ---> number: {temp.data.number}")
temp = temp.next
def add(name, number):
r_new = Record(name, number)
new_node = Node(data=r_new)
new_node.next = phone_book
phone_book.head = new_node
printList()
add("ahmet", "544")
printList()
rather than new_node.next = phone_book try new_node.next = phone_book.head
Thank you for answer JonSG
class Record:
def __init__(self, name, number):
self.name = name
self.number = number
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
r1 = Record(name="selman", number="541")
r2 = Record(name="mustafa", number="542")
r3 = Record(name="fatih", number="543")
r1_node = Node(data=r1)
r2_node = Node(data=r2)
r3_node = Node(data=r3)
phone_book = LinkedList()
phone_book.head = r1_node
r1_node.next = r2_node
r2_node.next = r3_node
def printList():
temp = phone_book.head
while temp:
print(f"name: {temp.data.name} ---> number: {temp.data.number}")
temp = temp.next
def add(name, number):
r_new = Record(name, number)
new_node = Node(data=r_new)
new_node.next = phone_book.head
phone_book.head = new_node
add("ahmet", "544")
printList()

Python - Parent method don't acess the value of variable children

Hi I'm having a problem in this classes I created the parent class extracao_nia with the method aplica_extracao for having the similar part of the execution that I use in others class and the diferent part is in the transform method definined in the children class
but I'm having an issue that the variables that I defined as list() are Null variable when I execute the code:
AttributeError: 'NoneType' object has no attribute 'append'
class extracao_nia:
def __init__(self, d=1, h=1, m=15):
self._data_base = "database"
self.UM_DIA = datetime.timedelta(days=d)
self.UMA_HORA = datetime.timedelta(hours=h)
self.INTERVALO = datetime.timedelta(minutes=m)
#property
def data_base(self):
return self._data_base
def aplica_extracao(self, SQL):
fim_intervalo = self.inicio + self.INTERVALO#
pbar = self.cria_prog_bar(SQL)#
while (fim_intervalo <= self.FIM):#
self.connector.execute(SQL,(self.inicio.strftime('%Y-%m-%d %H:%M'),fim_intervalo.strftime('%Y-%m-%d %H:%M')))#
for log in self.connector:#
self.transforma(log)
self.inicio = fim_intervalo
fim_intervalo = self.inicio + self.INTERVALO
class usuarios_unicos(extracao_nia):
def __init__(self, d=1, h=1, m=15, file='nodes.json'):
self._data_base = "database"
self.UM_DIA = datetime.timedelta(days=d)
self.UMA_HORA = datetime.timedelta(hours=h)
self.INTERVALO = datetime.timedelta(minutes=m)
self.file = file
self.ids = list()
self.nodes = list()
self.list_cpf = list()
def transforma(self, log):
context = json.loads(log[0])['context']
output = json.loads(log[0])['output']
try:
nr_cpf = context['dadosDinamicos']['nrCpf']
conversation_id = context['conversation_id']
nodes_visited = output['output_watson']['nodes_visited']
i = self.ids.index(conversation_id)
atual = len(self.nodes[i])
novo = len(nodes_visited)
if novo > atual:
nodes[i] = nodes_visited
except KeyError:
pass
except ValueError:
self.ids.append(conversation_id)
self.nodes = self.nodes.append(nodes_visited)
self.list_cpf = self.list_cpf.append(nr_cpf)
list.append returns None since it is an in-place operation, so
self.nodes = self.nodes.append(nodes_visited)
will result in self.nodes being assigned None. Instead you can just use
self.nodes += nodes_visited

Class inheritance type checking after pickling in Python

Is there a sure-fire way to check that the class of an object is a sub-class of the desired super?
For Example, in a migration script that I'm writing, I have to convert objects of a given type to dictionaries in a given manner to ensure two-way compatability of the data.
This is best summed up like so:
Serializable
User
Status
Issue
Test
Set
Step
Cycle
However, when I'm recursively checking objects after depickling, I receive a Test object that yields the following results:
Testing data object type:
type(data)
{type}< class'__main.Test' >
Testing Class type:
type(Test())
{type}< class'__main.Test' >
Testing object type against class type:
type(Test()) == type(data)
{bool}False
Testing if object isinstance() of Class:
isinstance(data, Test)
{bool}False
Testing if Class isinstance() of Super Class:
isinstance(Test(), Serializable)
{bool}True
Testing isinstance() of Super Class::
isinstance(data, Serializable)
{bool}False
Interestingly, it doesn't appear to have any such problem prior to pickling as it handles the creation of dictionary and integrity hash just fine.
This only crops up with depickled objects in both Pickle and Dill.
For Context, here's the code in it's native environment - the DataCache object that is pickled:
class DataCache(object):
_hash=""
_data = None
#staticmethod
def genHash(data):
dataDict = DataCache.dictify(data)
datahash = json.dumps(dataDict, sort_keys=True)
return hashlib.sha256(datahash).digest()
#staticmethod
def dictify(data):
if isinstance(data,list):
datahash = []
for item in data:
datahash.append(DataCache.dictify(item))
elif isinstance(data,(dict, collections.OrderedDict)):
datahash = collections.OrderedDict()
for key,value in datahash.iteritems():
datahash[key]= DataCache.dictify(value)
elif isinstance(data, Serializable):
datahash = data.toDict()
else:
datahash = data
return datahash
def __init__(self, restoreDict = {}):
if restoreDict:
self.__dict__.update(restoreDict)
def __getinitargs__(self):
return (self.__dict__)
def set(self, data):
self._hash = DataCache.genHash(data)
self._data = data
def verify(self):
dataHash = DataCache.genHash(self._data)
return (self._hash == dataHash)
def get(self):
return self._data
Finally, I know there's arguments for using JSON for readability in storage, I needed Pickle's ability to convert straight to and from Objects without specifying the object type myself. (thanks to the nesting, it's not really feasible)
Am I going mad here or does pickling do something to the class definitions?
EDIT:
Minimal Implementation:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import requests
from aenum import Enum
import json # _tricks
import base64
import argparse
import os
import sys
import datetime
import dill
import hashlib
import collections
class Serializable(object):
def __init__(self, initDict={}):
if initDict:
self.__dict__.update(initDict)
def __str__(self):
return str(self.sortSelf())
def sortSelf(self):
return collections.OrderedDict(sorted(self.__dict__.items()))
def toDict(self):
return self.__dict__
def fromDict(self, dict):
# Not using __dict__.update(...) to avoid polluting objects with the excess data
varMap = self.__dict__
if dict and varMap:
for key in varMap:
if (key in dict):
varMap[key] = dict[key]
self.__dict__.update(varMap)
return self
return None
class Issue(Serializable):
def __init__(self, initDict={}):
self.id = 0
self.key = ""
self.fields = {}
if initDict:
self.__dict__.update(initDict)
Serializable.__init__(self)
def fieldToDict(self, obj, key, type):
if key in obj:
result = obj[key]
else:
return None
if result is None:
return None
if isinstance(result, type):
return result.toDict()
return result
def fromDict(self, jsonDict):
super(Issue, self).fromDict(jsonDict)
self.fields["issuetype"] = IssueType().fromDict(self.fields["issuetype"])
self.fields["assignee"] = User().fromDict(self.fields["assignee"])
self.fields["creator"] = User().fromDict(self.fields["creator"])
self.fields["reporter"] = User().fromDict(self.fields["reporter"])
return self
def toDict(self):
result = super(Issue, self).toDict()
blankKeys = []
for fieldName, fieldValue in self.fields.iteritems():
if fieldValue is None:
blankKeys.append(fieldName)
if blankKeys:
for key in blankKeys:
self.fields.pop(key, None)
result["fields"]["issuetype"] = self.fieldToDict(result["fields"], "issuetype", IssueType)
result["fields"]["creator"] = self.fieldToDict(result["fields"], "creator", User)
result["fields"]["reporter"] = self.fieldToDict(result["fields"], "reporter", User)
result["fields"]["assignee"] = self.fieldToDict(result["fields"], "assignee", User)
return result
class IssueType(Serializable):
def __init__(self):
self.id = 0
self.name = ""
def toDict(self):
return {"id": str(self.id)}
class Project(Serializable):
def __init__(self):
Serializable.__init__(self)
self.id = 0
self.name = ""
self.key = ""
class Cycle(Serializable):
def __init__(self):
self.id = 0
self.name = ""
self.totalExecutions = 0
self.endDate = ""
self.description = ""
self.totalExecuted = 0
self.started = ""
self.versionName = ""
self.projectKey = ""
self.versionId = 0
self.environment = ""
self.totalCycleExecutions = 0
self.build = ""
self.ended = ""
self.name = ""
self.modifiedBy = ""
self.projectId = 0
self.startDate = ""
self.executionSummaries = {'executionSummary': []}
class Step(Serializable):
def __init__(self):
self.id = ""
self.orderId = 0
self.step = ""
self.data = ""
self.result = ""
self.attachmentsMap = {}
def toDict(self):
dict = {}
dict["step"] = self.step
dict["data"] = self.data
dict["result"] = self.result
dict["attachments"] = []
return dict
class Status(Serializable):
def __init__(self):
self.id = 0
self.name = ""
self.description = ""
self.isFinal = True
self.color = ""
self.isNative = True
self.statusCount = 0
self.statusPercent = 0.0
class User(Serializable):
def __init__(self):
self.displayName = ""
self.name = ""
self.emailAddress = ""
self.key = ""
self.active = False
self.timeZone = ""
class Execution(Serializable):
def __init__(self):
self.id = 0
self.orderId = 0
self.cycleId = -1
self.cycleName = ""
self.issueId = 0
self.issueKey = 0
self.projectKey = ""
self.comment = ""
self.versionId = 0,
self.versionName = "",
self.executedOn = ""
self.creationDate = ""
self.executedByUserName = ""
self.assigneeUserName = ""
self.status = {}
self.executionStatus = ""
def fromDict(self, jsonDict):
super(Execution, self).fromDict(jsonDict)
self.status = Status().fromDict(self.status)
# This is already listed as Execution Status, need to associate and convert!
return self
def toDict(self):
result = super(Execution, self).toDict()
result['status'] = result['status'].toDict()
return result
class ExecutionContainer(Serializable):
def __init__(self):
self.executions = []
def fromDict(self, jsonDict):
super(ExecutionContainer, self).fromDict(jsonDict)
self.executions = []
for executionDict in jsonDict["executions"]:
self.executions.append(Execution().fromDict(executionDict))
return self
class Test(Issue):
def __init__(self, initDict={}):
if initDict:
self.__dict__.update(initDict)
Issue.__init__(self)
def toDict(self):
result = super(Test, self).toDict()
stepField = "CustomField_0001"
if result["fields"][stepField]:
steps = []
for step in result["fields"][stepField]["steps"]:
steps.append(step.toDict())
result["fields"][stepField] = steps
return result
def fromDict(self, jsonDict):
super(Test, self).fromDict(jsonDict)
stepField = "CustomField_0001"
steps = []
if stepField in self.fields:
for step in self.fields[stepField]["steps"]:
steps.append(Step().fromDict(step))
self.fields[stepField] = {"steps": steps}
return self
class Set(Issue):
def __init__(self, initDict={}):
self.__dict__.update(initDict)
Issue.__init__(self)
class DataCache(object):
_hash = ""
_data = None
#staticmethod
def genHash(data):
dataDict = DataCache.dictify(data)
datahash = json.dumps(dataDict, sort_keys=True)
return hashlib.sha256(datahash).digest()
#staticmethod
def dictify(data):
if isinstance(data, list):
datahash = []
for item in data:
datahash.append(DataCache.dictify(item))
elif isinstance(data, (dict, collections.OrderedDict)):
datahash = collections.OrderedDict()
for key, value in datahash.iteritems():
datahash[key] = DataCache.dictify(value)
elif isinstance(data, Serializable):
datahash = data.toDict()
else:
datahash = data
return datahash
def __init__(self, restoreDict={}):
if restoreDict:
self.__dict__.update(restoreDict)
def __getinitargs__(self):
return (self.__dict__)
def set(self, data):
self._hash = DataCache.genHash(data)
self._data = data
def verify(self):
dataHash = DataCache.genHash(self._data)
return (self._hash == dataHash)
def get(self):
return self._data
def saveCache(name, projectKey, object):
filePath = "migration_caches/{projectKey}".format(projectKey=projectKey)
if not os.path.exists(path=filePath):
os.makedirs(filePath)
cache = DataCache()
cache.set(object)
targetFile = open("{path}/{name}".format(name=name, path=filePath), 'wb')
dill.dump(obj=cache, file=targetFile)
targetFile.close()
def loadCache(name, projectKey):
filePath = "migration_caches/{projectKey}/{name}".format(name=name, projectKey=projectKey)
result = False
try:
targetFile = open(filePath, 'rb')
try:
cache = dill.load(targetFile)
if isinstance(cache, DataCache):
if cache.verify():
result = cache.get()
except EOFError:
# except BaseException:
print ("Failed to load cache from file: {filePath}\n".format(filePath=filePath))
except IOError:
("Failed to load cache file at: {filePath}\n".format(filePath=filePath))
targetFile.close()
return result
testIssue = Test().fromDict({"id": 1000,
"key": "TEST",
"fields": {
"issuetype": {
"id": 1,
"name": "TestIssue"
},
"assignee": "Minothor",
"reporter": "Minothor",
"creator": "Minothor",
}
})
saveCache("Test", "TestProj", testIssue)
result = loadCache("Test", "TestProj")
EDIT 2
The script in it's current form, now seems to work correctly with vanilla Pickle, (initially switched to Dill due to a similar issue, which was solved by the switch).
However, if you are here with this issue and require Dill's features, then as Mike noted in the comments - it's possible to change the settings in dill.settings to have Dill behave pickle referenced items only with joblib mode, effectively mirroring pickle's standard pickling behaviour.

Why do I keep getting the error: AttributeError: 'int' object has no attribute 'subject'

So I am creating a code what are the co requisites and which courses students can take next by specifying a specific course. For example, if the user inputs "ECE 256", then co requisites should be ECE 256L and the next class they can take is ECE 304.
List.print_list()
File /Users/marleneterrones/Dropbox/ECE 480 Group/linked list/node.py, line 45, in,
print_list
result = result + str(dataObj.subject)
AttributeError: 'str' object has no attribute 'subject'
class Node:
def __init__(self, subject=None, corec=[] , next_class=[]):
self.subject = subject
self.corec = corec
self.next_class = next_class
class LinkedList:
def __init__(self):
self.firstNode = Node(None, None, None)
self.lastNode = self.firstNode
self.size = 0
def add(self, subject,corec):
"""Add a node to the list"""
node = Node(subject , corec ,None)
node.subject = subject;
node.corec = corec;
if self.firstNode.subject == None:
self.firstNode = node
self.lastNode = node
else:
self.lastNode.next_class = node
self.lastNode = node
self.size += 1
def print_list(self):
"""prints whats ever in the array """
result = ""
currentNode = Node( None,None, None)
currentNode = self.firstNode
i = 0
result = result + "("
while currentNode != None:
if i > 0:
result = result + ","
dataObj = currentNode.subject
dataObj2 = currentNode.corec
if dataObj != None:
result = result + str(dataObj.subject)
if dataObj2 != None:
result = result + str(dataObj2.corec)
currentNode = currentNode.next_class
i = i + 1
result = result + ")"
return result
dataObj = currentNode.subject makes dataObj maybe an int, then dataObj.subject causes such an error. You may just want
result = result + str(dataObj)
there are some needless code in you snippet, e.g.:
node = Node(subject , corec ,None)
node.subject = subject;
node.corec = corec;
the 2 latter lines are not necessary since you've already initialized node with subject and corec.

Categories