开发者

Generating a dynamic time delta: python

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.__dete开发者_如何学运维rmineTimeDelta(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?


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:

  • The Official Python Tutorial
  • PEP 3102: Keyword-Only Arguments


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜