0

I have a few files with python code and decorators like this:

@trace('api.module.function_name', info=None, custom_args=False)

The only difference between these decorators is the string 'api.module.function_name' - func name and module are different. And depending on the this param name sometimes this decorator is one-lined, some times it is two- or three-lined.

I want to replace these decorators with the other one - more simple, like "@my_new_decorator".

I thought about some regex but I have no idea if it's possible for such "fuzzy" search. I tried ^@trace([A-Za-z0-9]\, custom_args=False)$ But it doesn't work.

Is there a way to do it?

2
  • Well a regex like that wouldn't work, you'd need something more like ^\s*@trace\(.+\)$ because you're matching one alphanumeric character and only matching at all if this is all at column 0. Commented Jul 29, 2016 at 12:01
  • you might need the multiline flag in your regex : re.M Commented Jul 29, 2016 at 12:06

2 Answers 2

1

Something like this should work:

(\n|^)\s*@trace\(\s*'[^']*',\s*info=None,\s*custom_args=False\s*\)\s*(\r|\n|$)

See the demo

Sign up to request clarification or add additional context in comments.

Comments

1

Use ^@trace\('api\.(.+)\.(.+)', info=None, custom_args=False\)$ with a multiline flag.

You may want to use re.sub :

>>> import re
>>> pattern = re.compile('^@trace\('api\.(.+)\.(.+)', info=None, custom_args=False\)$', re.M)
>>> re.sub(pattern, '@my_new_decorator('\1', '\2')', '@trace('api.module.function_name', info=None, custom_args=False)')
@my_new_decorator('module', 'function_name')

See this for the demo of the regex

As you can see \1 expand to the first group in the regex (.+)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.