I get 'global name [function name] is not defined' when I try to reference a function I previously defined

2.4k views Asked by At

Basically, here's the format of my code:

class SomeClass():

    # RegEx to remove all non-alphanumeric characters from a string
    def alphaNum(original):
        return str(re.sub(r'[^a-zA-Z0-9]','', original))


    # Write to xlsx file =====================================================
    def write(self):
        #CODE###
        uglyString = 'asasdf-)aws'

        print alphaNum(uglyString)
        #I've also tried calling self.alphaNum(uglyString), for what it's worth

and I get "global name 'alphaNum' is not defined" when I call write from another file (details left out, but I know the print statement is where the error occurs)

I'm positive I'm overlooking something dumb, I (like to think that I) have a good handle on scope, defining things before using them, etc.

edit:

Thanks for the help guys! I ended up just moving alphaNum() outside of the class. And for those interested, the actual purpose of this is dealing with the quirks of Amazon's boto interface for CloudFormation. It'll happily return asset id values with '-' in them, then complain that you can't have any in a template. Such is life...

1

There are 1 answers

6
Mike DeSimone On BEST ANSWER

That's because alphaNum is a member of SomeClass. Further, it's not a staticmethod, so the first parameter should be self.

I'm not really sure why you're putting all this in a class, but it should look like this instead:

class SomeClass():

    @staticmethod
    def alphaNum(original):
        """RegEx to remove all non-alphanumeric characters from a string"""
        return str(re.sub(r'[^a-zA-Z0-9]','', original))

    def write(self):
        """Write to xlsx file"""

        uglyString = 'asasdf-)aws'

        print SomeClass.alphaNum(uglyString)