Philipp_Kats
Philipp_Kats

Reputation: 4212

Python: "method variables" for independent function

I am compiling a regex pattern to use it multiple times.

However, I want to use it inside a function, so for now I use it as a global variable. However, I don't need it outside of this specific function, so I wonder if I can write it as a static variable, meaning it would be compiled once and for all function instances/occurrences.

import re
p = re.compile(“[0-9|-]+”)

def search(txt):
    global p

    # some stuff
    return p.search(txt).group(0)

PS of course, in this specific example, It won't save me any sufficient​ amount of memory, I just want to find if I can do this in general. Also, it would me more readable that way, I think.​

Upvotes: 0

Views: 216

Answers (2)

Kevin
Kevin

Reputation: 30151

In C, a "static variable" is just a global variable that's only visible within one function.* The term "static" has other meanings in other languages, but this is obviously the one OP meant.

Python does not have static variables of this variety. If you only want your global variable used in one function, than you only use it in that one function. Globals never shadow anything besides builtins, so this shouldn't be difficult provided you choose a reasonable variable name (PEP 8 recommends ALL_CAPS for global constants). Globals are also encapsulated by their module, so namespace pollution shouldn't be too much of a problem either.

There is nothing wrong, design-wise, with constant global variables. A pattern that is compiled once and never altered is no different from any other global constant.

* Technically, it's usually defined the other way around (a global variable is a globally-visible static variable), but I'm phrasing it this way for convenience.

Upvotes: 2

Tyler
Tyler

Reputation: 18177

You could put it all in an object, and then the compiled regular expression would be an instance variable:

import re

class Searcher:

    def __init__(self):
        self.p = re.compile("[0-9|-]+")

    def search(self, text):
        return self.p.search(text).group(0)

s = Searcher()

# Use it as much as you want now
print s.search("123-345")
print s.search("123-abc")

Upvotes: 0

Related Questions