2

I am trying to parametrize a function using decorator. Finally I am able to get it run as expected after lot of hit and trials. But still I am not satisfied as though it is working, it doesn't seem to be right way to do it.

Please help me improve this code.

Here is my code:

def WarmWelcome(fn):
    def wrapped(DataProvider):
       for name in DataProvider(): 
         print fn(name) + ":)"
    return wrapped

def DataProvider():
    names=["abc","xyz","def"]
    for name in names:
        yield name

@WarmWelcome
def hello(name):
    return "hello " +name

hello(DataProvider) 

Here is the updated code:

def WarmWelcome(DataProvider):
  def real_decorator(fn):
    def wrapped():
       for name in DataProvider(): 
         print fn(name) + ":)"
    return wrapped
  return real_decorator

def DataProvider():
    names=["abc","xyz","def"]
    for name in names:
        yield name
@WarmWelcome(DataProvider)
def hello(name):
    return "hello " +name

hello() 
Vishal Aggarwal
  • 1,929
  • 1
  • 13
  • 23
  • Looks fine to me. What's the problem, exactly? – Aya Apr 27 '13 at 13:54
  • As per my understanding the better way would be to pass the DataProvider through decorator function.Something like this:@WarmWelcome(DataProvider()) but I could not get it run this way. – Vishal Aggarwal Apr 27 '13 at 14:07
  • 1
    @vishul9, see [this answer](http://stackoverflow.com/a/5929165/521590) on how to implement a decorator with arguments. – gatto Apr 27 '13 at 14:19

1 Answers1

1

It's also possible to provide dataset right to WarmWelcome decorator:

def WarmWelcome(*data_sets):
    def _decorator(func):
        def _func():
            for ds in data_sets:
                func(*ds)
        return _func
    return _decorator

@WarmWelcome(
    ("abc", ),
    ("xyz", ),
    ("def", ),
)
def hello(name):
    return "hello " +name

Original: PHPUnit-like dataProvider implementation for Python unittest

renskiy
  • 1,330
  • 1
  • 13
  • 12
  • 1
    Note that [link-only answers](http://meta.stackoverflow.com/tags/link-only-answers/info) are discouraged, SO answers should be the end-point of a search for a solution (vs. yet another stopover of references, which tend to get stale over time). Please consider adding a stand-alone synopsis here, keeping the link as a reference. – kleopatra Nov 21 '13 at 15:38
  • I think you need to put your strings in 1-tuples or do something other than unpacking them as arguments to the wrapped function for this to work. As written, if you call `hello()` you'll get an error from unpacking the string and calling the original function with two many arguments, e.g.: `hello('a', 'b', 'c')`. If you call `hello("Bob")` you get a different error about `_func` not taking any positional arguments. Usually a decorator shouldn't change the call signature of a method! – Blckknght Nov 22 '13 at 06:12