0

I am new to python. I would like to make this part of the variables shared across the functions.

     publist = []
     publication = {"pubid" : 1, "title" : 2, "year" : 3, "pubtype" : 4, "pubkey" :5}
     article = False
     book = False
     inproceeding = False
     incollection = False
     pubidCounter = 0

Where do i place the variables in these. I have tried placing it as shown below but it says there is an error with indendation. However, placing them outside returns an error too of indentation.

import xml.sax


class ABContentHandler(xml.sax.ContentHandler):
     publist = []
     publication = {"pubid" : 1, "title" : 2, "year" : 3, "pubtype" : 4, "pubkey" :5}
     article = False
     book = False
     inproceeding = False
     incollection = False
     pubidCounter = 0

    def __init__(self):
        xml.sax.ContentHandler.__init__(self)

    def startElement(self, name, attrs):

        if name == "incollection":
            incollection = true
            publication["pubkey"] = attrs.getValue("pubkey")
            pubidCounter += 1

        if(name == "title" and incollection):
            publication["pubtype"] = "incollection"



    def endElement(self, name):
        if name == "incollection":

            publication["pubid"] = pubidCounter
            publist.add(publication)
            incollection = False

    #def characters(self, content):


def main(sourceFileName):
    source = open(sourceFileName)
    xml.sax.parse(source, ABContentHandler())


if __name__ == "__main__":
    main("dblp.xml")

2 Answers 2

2

When placing them like that you define them as local for the class, thus you need to retrieve them through self

e.g.

def startElement(self, name, attrs):

    if name == "incollection":
        self.incollection = true
        self.publication["pubkey"] = attrs.getValue("pubkey")
        self.pubidCounter += 1

    if(name == "title" and incollection):
        self.publication["pubtype"] = "incollection"

If you would rather for them to be global, you should define them outside the class

Sign up to request clarification or add additional context in comments.

Comments

1

When you place the variables in the class definition, you can reference these variables in this way: self.incollection( self is the class instance ). If you don't do this( just reference these variables by their name, such as incollection), Python will try to find the these variables in global scope. So you can define them to be global and use the global keyword before reference these variables:

global incollection
incollection = true

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.