Question

Here's 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 dynamically 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.

Are there any better ways to do it?

Was it helpful?

Solution

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:

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top