创建集合时处理空 *args 的 pythonic 方法是什么?

发布于 2024-10-05 02:27:31 字数 1900 浏览 8 评论 0原文

定义一个函数

MyFunction(argument, *args): [对 *args 中的 arg 对 argument[arg] 执行某些操作]

如果 *args 为空,则该函数不会执行任何操作,但我想设置默认行为“如果 *args 的长度 == 0,则使用整个集合”

def Export(source, target, *args, sep=','):
    for item in source:
        SubsetOutput(WriteFlatFile(target), args).send(item[0])

我不想在每次迭代时检查 args 的长度,并且我无法访问 源中的项目直到迭代开始...

所以我可以,

if len(args) != 0:
   for item in source:

else
   for item in source:

这可能会工作,但看起来不够“Pythonic”?

这是(是否有)一种处理 *args 或 **kwargs 的标准方法以及两者为空时的默认行为?

更多代码:

def __coroutine(func):
    """
    a decorator for coroutines to automatically prime the routine
    code and method from 'curous course on coroutines and concurrency'
    by david beazley www.dabeaz.com
    """

    def __start(*args, **kwargs):
        cr = func(*args, **kwargs)
        next(cr)
        return cr
    return __start


def Export(source, target, *args, sep=','):
    if args:
        for item in source:
            SubsetOutput(WriteFlatFile(target, sep), args).send(item)
    else:
        for item in source:
            WriteFlatFile(target, sep).send(item)

@__coroutine
def SubsetOutput(target, *args):
    """
    take *args from the results and pass to target

    TODO
    ----
    raise exception when arg is not in result[0]
    """
    while True:
        result = (yield)
        print([result.arg for arg in result.dict() if arg in args])
        target.send([result.arg for arg in result.dict if arg in args])


@__coroutine
def WriteFlatFile(target, sep):
    """
    take set of results to a flat file

    TODO
    ----
    """
    filehandler = open(target, 'a')
    while True:
        result = (yield)
        line = (sep.join([str(result[var]) for
                        var in result.keys()])).format(result)+'\n'
        filehandler.write(line)

Defining a function,

MyFunction(argument, *args):
[do something to argument[arg] for arg in *args]

if *args is empty, the function doesn't do anything, but I want to make the default behavior 'use the entire set if length of *args == 0'

def Export(source, target, *args, sep=','):
    for item in source:
        SubsetOutput(WriteFlatFile(target), args).send(item[0])

I don't want to check the length of args on every iteration, and I can't access the keys of
item in source until the iteration begins...

so i could

if len(args) != 0:
   for item in source:

else
   for item in source:

which will probably work but doesn't seem 'pythonic' enough?

is this (is there) a standard way to approach *args or **kwargs and default behavior when either is empty?

More Code:

def __coroutine(func):
    """
    a decorator for coroutines to automatically prime the routine
    code and method from 'curous course on coroutines and concurrency'
    by david beazley www.dabeaz.com
    """

    def __start(*args, **kwargs):
        cr = func(*args, **kwargs)
        next(cr)
        return cr
    return __start


def Export(source, target, *args, sep=','):
    if args:
        for item in source:
            SubsetOutput(WriteFlatFile(target, sep), args).send(item)
    else:
        for item in source:
            WriteFlatFile(target, sep).send(item)

@__coroutine
def SubsetOutput(target, *args):
    """
    take *args from the results and pass to target

    TODO
    ----
    raise exception when arg is not in result[0]
    """
    while True:
        result = (yield)
        print([result.arg for arg in result.dict() if arg in args])
        target.send([result.arg for arg in result.dict if arg in args])


@__coroutine
def WriteFlatFile(target, sep):
    """
    take set of results to a flat file

    TODO
    ----
    """
    filehandler = open(target, 'a')
    while True:
        result = (yield)
        line = (sep.join([str(result[var]) for
                        var in result.keys()])).format(result)+'\n'
        filehandler.write(line)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

故人如初 2024-10-12 02:27:31

只需检查它不是 none,您不必创建单独的参数

def test(*args):
    if not args:
        return #break out
    return True #or whatever you want

Just check its not none, you don't have to create a separate argument

def test(*args):
    if not args:
        return #break out
    return True #or whatever you want
油焖大侠 2024-10-12 02:27:31

有没有办法将“整个集合”参数传递给 SubsetOutput,这样您就可以将条件隐藏在其调用中,而不是使用显式的 if?例如,这可以是 None[]

# Pass None to use full subset.
def Export(source, target, *args, sep=','):
    for item in source:
        SubsetOutput(WriteFlatFile(target), args or None).send(item[0])

# Pass an empty list [] to use full subset. Even simpler.
def Export(source, target, *args, sep=','):
    for item in source:
        SubsetOutput(WriteFlatFile(target), args).send(item[0])

如果没有,我会采用两个循环解决方案,假设循环确实是一条线。它读起来很好,并且是一些代码重复的合理用例。

def Export(source, target, *args, sep=','):
    if args:
        for item in source:
            SubsetOutput(WriteFlatFile(target), args).send(item[0])
    else:
        for item in source:
            FullOutput(WriteFlatFile(target)).send(item[0])

Is there a way to pass an "entire set" argument to SubsetOutput, so you can bury the conditional inside its call rather than have an explicit if? This could be None or [], for example.

# Pass None to use full subset.
def Export(source, target, *args, sep=','):
    for item in source:
        SubsetOutput(WriteFlatFile(target), args or None).send(item[0])

# Pass an empty list [] to use full subset. Even simpler.
def Export(source, target, *args, sep=','):
    for item in source:
        SubsetOutput(WriteFlatFile(target), args).send(item[0])

If not, I would go with the two loop solution, assuming the loop really is a single line. It reads well and is a reasonable use case for a little bit of code duplication.

def Export(source, target, *args, sep=','):
    if args:
        for item in source:
            SubsetOutput(WriteFlatFile(target), args).send(item[0])
    else:
        for item in source:
            FullOutput(WriteFlatFile(target)).send(item[0])
方觉久 2024-10-12 02:27:31

这个怎么样:

def MyFunc(argument, *args):
    ( DoSomething for i in (filter(args.__contains__ ,argument) if args else argument) )

How about this:

def MyFunc(argument, *args):
    ( DoSomething for i in (filter(args.__contains__ ,argument) if args else argument) )
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文