8

I need to replace, in a large number of Python files with many function definitions, all occurrences of

def some_func(foo, bar):

with

@jit(parallel=True)
def some_func(foo, bar):

with whatever level of indentation def some_func(foo, bar) has.

Example: I want to replace

def some_func_1(foo, bar):
def some_func_2(foo, bar):

    def some_func_3(foo, bar):

def some_func_4(foo, bar):

with

@jit(parallel=True)
def some_func_1(foo, bar):
@jit(parallel=True)
def some_func_2(foo, bar):

    @jit(parallel=True)
    def some_func_3(foo, bar):

@jit(parallel=True) def some_func_4(foo, bar):

Motivation: I want to "brute-force accelerate/parallelize" a FDTD simulation package without having to rewrite the entire codebase by making use of numba's automatic parallelization with @jit.

PS.: Any comment/critique of this naive approach of (ab)using @jit is also welcome (e.g. if this wouldn't work at all)!

srhslvmn
  • 259
  • 2
  • 12

4 Answers4

13

This will work for any kind of spaces (white spaces or tabulations) and for any kind of linebreak \n, \r\n, \r.


  • Ctrl+H
  • Find what: ^(\h*)(?=def\b.*(\R))
  • Replace with: $1@jit\(parallel=True\)$2$1
  • TICK Match case
  • TICK Wrap around
  • SELECT Regular expression
  • UNTICK . matches newline
  • Replace all

Explanation:

^           # beginning of line
    (           # group 1
        \h*         # 0 or more horizontal spaces
    )           # end group
    (?=         # positive lookahead, make sure we have after:
        def\b       # literally "def" and a word boundary, in order to not match "default"
        .*          # 0 or more any character but newline
        (\R)        # group 2, any kind of linebreak
    )           # end lookahead

Replacement:

$1                      # content of group 1, the spaces to insert
@jit\(parallel=True\)   # literally
$2                      # content of group 2, the linebreak used in the file
$1                      # content of group 1, the spaces to insert

Screenshot (before):

enter image description here

Screenshot (after):

enter image description here

Toto
  • 19,304
6

A better solution may be using jit_module to jit all your functions automatically

ihall
  • 76
4

You can do that using Regex capture groups and then reusing the first group (the indentation) on both lines in the replacement.

Search (with Regex):

(^.*)(def .*\([^\(]+\))

And replace with:

\1@jit\(parallel=True\)\r\n\1\2

See in action: enter image description here

Nelson
  • 1,393
Yisroel Tech
  • 13,220
-1

In Notepad++, searching for (^.*)(def ) (with space at the end) and replacing with \1@jit\(parallel=True\)\r\n\1\2 works. The space at the end is important as otherwise strings such as default will also get replaced.

srhslvmn
  • 259
  • 2
  • 12