2

Is there a way to do something like that in python?

def foo(str(arg).lower()):
    print arg

foo('LOL')

I wanted to create decorator in the first place but whatever i try i could not get it to work as I wanted, i either get generator returned or list.

Edit: This is what I wanted to accomplish.

def to_lowercase(function):
    def wrapper(*args):
        return function(*[x.lower() if isinstance(x, str) else x for x in args])
    return wrapper
Sir DrinksCoffeeALot
  • 593
  • 2
  • 11
  • 20

1 Answers1

5

its possible to write a decorator to do what you seek:

decorators are functions that accept a function as the first argument and arguments as next arguments. Then a different function is returned, or the arguments are modified in some way before being applied to the input-function.

Here we can modify the arguments to lower case if they are instances of str and leave unaltered otherwise using comprehensions:

def tolower(f, *args, **kwargs):
    def newfun(*args, **kwargs):
        as_ = [a.lower() if isinstance(a, str) else a for a in args]
        kws_ = {k: (v.lower() if isinstance(v, str) else v) for k,v in kwargs.items()}
        return f(*as_, **kws_)
    return newfun

@tolower
def print_lower(x, y, z):
    print(x)
    print(y)
    print(z)

print_lower('A', 'B', 1)
# outputs
a
b
1
Haleemur Ali
  • 26,718
  • 5
  • 61
  • 85