A decorator to replace specific string in function to another string

python decorator with arguments
python class decorator with arguments
decorators can be chained
python class decorator add method
python decorator stackoverflow
classes can also be decorated, if required, in python.
decorators in python tutorialspoint
decorator function log in python

Is it possible to do like this ?

def my_func():
    my_list = ['abc', 'def', 'ghi']
    my_str = 'abc'

If I pass A to decorator -> replace 'abc' to 'xxx' in function, pass B -> yyy

@decorator('abc')

def my_func():
    my_list = ['xxx', 'def', 'ghi']
    my_str = 'xxx'

I don't know whether it's possible or not.

How can I do with this?


You can use a decorator that uses ast.NodeTransformer to modify any string node with the target value with the given replacement in the function's AST:

import ast
import inspect
from textwrap import dedent

class Replace(ast.NodeTransformer):
    def __init__(self, target, replacement):
        self.target = target
        self.replacement = replacement

    def visit_Str(self, node):
        if node.s == self.target:
            node.s = self.replacement
        return node

    # remove 'replace' from the function's decorator list to avoid re-decorating during exec
    def visit_FunctionDef(self, node):
        node.decorator_list = [
            decorator for decorator in node.decorator_list
            if not isinstance(decorator, ast.Call) or decorator.func.id != 'replace'
        ]
        self.generic_visit(node)
        return node

def replace(target, repl):
    def decorator(func):
        tree = Replace(target, repl).visit(ast.parse(dedent(inspect.getsource(func))))
        ast.fix_missing_locations(tree)
        scope = {}
        exec(compile(tree, inspect.getfile(func), "exec"), func.__globals__, scope)
        return scope[func.__name__]
    return decorator

so that:

@replace('abc', 'xxx')
def my_func():
    my_list = ['abc', 'def', 'ghi']
    my_str = 'abc'
    print(my_list, my_str)

my_func()

outputs:

['xxx', 'def', 'ghi'] xxx

Demo: https://repl.it/@blhsing/ValuableLimeVideogames

Advanced Uses of Decorators, This has certain unfortunate side effects: mostly, the name of the function appears to change to the name of the wrapper function from inside the decorator, and the To make sure the decorated function retains its name and docstring, those to functions the same way as you can to most of the other objects in Python). The Replace function replaces a specified part of a string with another string a specified number of times. Syntax Replace(string,find,replacewith[,start[,count[,compare]]])


It's possible to replace the code object of a function with a decorator thereby replacing constants inside of it, but it's unlikely to be the solution you actually want to go with.

This would get unmaintainable at nearly any scale as you'd have large sections looking like:

# Note, this is python 3.x specific
CodeType(
    argcount,             #   integer
    kwonlyargcount,       #   integer
    nlocals,              #   integer
    stacksize,            #   integer
    flags,                #   integer
    codestring,           #   bytes
    consts,               #   tuple
    names,                #   tuple
    varnames,             #   tuple
    filename,             #   string
    name,                 #   string
    firstlineno,          #   integer
    lnotab,               #   bytes
    freevars,             #   tuple
    cellvars,             #   tuple
)

In which you need to make copies from the original code object, modifying them to your intent.

A better solution to this sort of problem would be to allow passing the string to the function as a parameter. If you needed the function to later be callable without the string present, you could use a partial (see functools.partial)

Code. Changing it without breaking it, using a Decorator., How I used Python's decorator feature to change a piece of user The task was to make the view_connectome() consistent with another, older function We wanted to change the names of certain parameters in the function signature: function body, make the appropriate changes in the docstring aaand. Dim aString As String = Replace(TestString, "o", "i") Remarks The return value of the Replace function is a string that begins at the position specified by Start and concludes at the end of the Expression string, with the substitutions made as specified by the Find and Replace values.


Decorator can't change logic inside of your function. You can either do operation on arguments or whatever you are returning. In your case you can use post decorator

Primer on Python Decorators – Real Python, By definition, a decorator is a function that takes another function and extends the and be_awesome() are regular functions that expect a name given as a string. function, the way a decorator modifies a function can change dynamically. So the string after @ will be replaced with my defined string irrespective of the data received in procedure. Tried Replace method but it didn't work. I know that i need to use charindex, substring & left functions to make it work but not getting the right combination.


DOC: Replace old string formatting syntax in calling of Appender , I found calling of @Appender() are using % to format string. Be more specific, the template using % to formate will be something like function when it didn't use doc decorator originally but some other functions want to use  replace_string. Is a string or an expression that evaluates to a string which specifies the replacement string. The replace_string is optional. If you skip it, the function will do nothing. If any argument is NULL, the REPLACE () function will return NULL. The REPLACE () function is very useful for clean up data.


Python Decorator Tutorial with Example, A function can be assigned to a variable, passed to another function and can be When we use a decorator, we are replacing one functions with another. def decorator(func): """decorator docstring""" def inner_function(*args,  replace() is an inbuilt function in Python programming language that returns a copy of the string where all occurrences of a substring is replaced with another substring. Syntax : string.replace(old, new, count)


Python Tutorial: Easy Introduction into Decorators and Decoration, A reference to a function "func" or a class "C" is passed to a decorator and the decorator Another example using "proper" return statements in the functions: In our main program, all we have to do is change the import statement to Hi, f returns: function name: f docstring: just some silly function module name: __main​__ In this post we’re going to explore how to find and replace multiple text strings from within another string. Download Example File Excel has a great built in function called SUBSTITUTE which allows you to find one bit of text within another text string and substitute it for another bit of text.