Deutsch   English   Français   Italiano  
<advice-20230903173607@ram.dialup.fu-berlin.de>

View for Bookmarking (what is this?)
Look up another Usenet article

Path: eternal-september.org!news.eternal-september.org!fu-berlin.de!uni-berlin.de!not-for-mail
From: ram@zedat.fu-berlin.de (Stefan Ram)
Newsgroups: comp.lang.python
Subject: Re: Passing info to function used in re.sub
Date: 3 Sep 2023 16:53:02 GMT
Organization: Stefan Ram
Lines: 37
Expires: 1 Sep 2024 11:59:58 GMT
Message-ID: <advice-20230903173607@ram.dialup.fu-berlin.de>
References: <mailman.268.1693757502.23016.python-list@python.org>
Mime-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
X-Trace: news.uni-berlin.de BrYugGJuW2Ge5/xXEkLHXg/waijBwuI5vIm15tbFjcfZ/M
Cancel-Lock: sha1:53bHgnL4kYJHjBpa/CncuCSHvCw= sha256:132AGEgnzybtfQlJojV4WwxkXvweABgHpZJ92PYtEzs=
X-Copyright: (C) Copyright 2023 Stefan Ram. All rights reserved.
	Distribution through any means other than regular usenet
	channels is forbidden. It is forbidden to publish this
	article in the Web, to change URIs of this article into links,
        and to transfer the body without this notice, but quotations
        of parts in other Usenet posts are allowed.
X-No-Archive: Yes
Archive: no
X-No-Archive-Readme: "X-No-Archive" is set, because this prevents some
	services to mirror the article in the web. But the article may
	be kept on a Usenet archive server with only NNTP access.
X-No-Html: yes
Content-Language: en-US
Accept-Language: de-DE-1901, en-US, it, fr-FR

=?utf-8?q?Jan_Erik_Mostr=C3=B6m?= <lists@mostrom.pp.se> writes:
>def fix_stuff(m):
>	# that what's available in m
>	replacement_text = m.group(1) + global_var1 + global_var2
>	return replacement_text
....
>new_text = re.sub(im_pattern,fix_stuff,md_text)

  You can use a closure:

import re

def make_replace( was_global_1, was_global_2 ):
    def replace( matcher ):
        return matcher.group( 1 )+ was_global_1 + was_global_2
    return replace

replace = make_replace( "a", "b" )

print( re.sub( r'(.)', replace, 'x' ))

  . Note how I wrote code one can actually execute. 
  You could have done this too! 

  Or, partial application:

import functools
import re

def replace( was_global_1, was_global_2, matcher ):
    return matcher.group( 1 )+ was_global_1 + was_global_2

print( re.sub( r'(.)', functools.partial( replace, 'a', 'b' ), 'x' ))

  .