I’m writing a utility module for easy handling of data text files. I have declared some module-level constants to provide default values to my methods arguments since for now I only use these values but I want my code to be easily adaptable.
But some constants aren’t easily hard-coded. For example re‘s pattern objects I can only get with re.compile. So I’ve written
import re
_my_fine_pattern_string = r"some obnoxious regex"
MY_FINE_PATTERN = re.compile(_my_fine_pattern_string)
def spam(eggs):
...
It worked yesterday within a script I directly execute. But now I wonder. Will this code be executed on import? Will it slow the execution? Will I be burned for doing this? Is there a better/faster way to do it?
Yes, this is fine. It will be executed on import. If you have a significant amount of computation to do (which
re.compileisn’t), it will slow down the import — but this is as it should be, since you need the constants to do your work anyway.Why are you using double-underscore names? If the constants are meant to be exported they should not be prefixed with underscores, and if not then they should have a single underscore. (Double has a specific meaning in the context of class inheritance but shouldn’t generally be used anywhere else.)