On 9/3/2023 12:10 PM, Jan Erik Moström via Python-list wrote:
I'm looking for some advice for how to write this in a clean way

I want to replace some text using a regex-pattern, but before creating 
replacement text I need to some file checking/copying etc. My code right now 
look something like this:

def fix_stuff(m):
        # Do various things that involves for info
        # that what's available in m
        replacement_text = m.group(1) + global_var1 + global_var2
        return replacement_text

and the call comes here

global_var1 = "bla bla"
global_var2 = "pff"

new_text = re.sub(im_pattern,fix_stuff,md_text)


The "problem" is that I've currently written some code that works but it uses 
global variables ... and I don't like global variables. I assume there is a better way to 
write this, but how?

= jem

There are two things to keep in mind here, I think. First, in Python a "global" variable is really module-level, so variables specific to one module seem fine and are common practice.

Second, the way you have written this example, it looks like these module-level "variables" are in effect constants. In other words, they are just shorthand for specific declared quantities. If this is so, then it makes even more sense to define them as module-level objects in the module that needs to use them.

If you still don't want to use them as "global" in your module, then define them in a separate module and import them from that module.

--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to