views:

212

answers:

2

Hello all.

Heres my situation:

import foo, bar, etc

frequency = ["hours","days","weeks"]

class geoProcessClass():

    def __init__(self,geoTaskHandler,startDate,frequency,frequencyMultiple=1,*args):
        self.interval = self.__determineTimeDelta(frequency,frequencyMultiple)

    def __determineTimeDelta(self,frequency,frequencyMultiple):
        if frequency in frequency:
            interval = datetime.timedelta(print eval(frequency + "=" + str(frequencyMultiple)))
            return interval
        else:
            interval = datetime.timedelta("days=1")
            return interval

I want to dinamically define a time interval with timedelta, but this does not seem to work.

Is there any specific way to make this work? I'm getting invalid syntax here.

Any better ways to do it?

+3  A: 

You can call a function with dynamic arguments using syntax like func(**kwargs) where kwargs is dictionary of name/value mappings for the named arguments.

I also renamed the global frequency list to frequencies since the line if frequency in frequency didn't make a whole lot of sense.

class geoProcessClass():
    def __init__(self, geoTaskHandler, startDate, frequency, frequencyMultiple=1, *args):
        self.interval = self.determineTimeDelta(frequency, frequencyMultiple)

    def determineTimeDelta(self, frequency, frequencyMultiple):
        frequencies = ["hours", "days", "weeks"]

        if frequency in frequencies:
            kwargs = {frequency: frequencyMultiple}
        else:
            kwargs = {"days": 1}

        return datetime.timedelta(**kwargs)

For what it's worth, stylistically it's usually frowned upon to silently correct errors a caller makes. If the caller calls you with invalid arguments you should probably fail immediately and loudly rather than try to keep chugging. I'd recommend against that if statement.

For more information on variable-length and keyword argument lists, see:

John Kugelman
+1 for keyword argument solution. It should be `kwargs = {'days': 1}`, though.
Blixt
Ah, you fixed it, nevermind =)
Blixt
Thanks for the help!
George
I've seen the mistype (lack of str delimiters, but thats just great)Do you guys know where i can get references for the use of **kwargs within functions? *args mean as many arguments as needed, correct? and **kwars mean dictionarys of variables with values?
George
google provides. http://www.saltycrane.com/blog/2008/01/how-to-use-args-and-kwargs-in-python/
JonahSan
Add a default value for `frequency` in `__init__` (`"days"`) and you can remove the troublesome quash-error-silently check.
Roger Pate
A: 

Your use of print eval(...) looks a bit over-complicated (and wrong, as you mention).

If you want to pass a keyword argument to a function, just do it:

interval = datetime.timedelta(frequency = str(frequencyMultiple)

I don't see a keyword argument called frequency though, so that might be a separate problem.

unwind