自定义占位符,如python中的None [英] Custom placeholder like None in python

查看:164
本文介绍了自定义占位符,如python中的None的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用另一个函数的函数中使用 argspec 或方法作为参数,并返回如下这样的元组:

I'm using argspec in a function that takes another function or method as the argument, and returns a tuple like this:

(("arg1", obj1), ("arg2", obj2), ...)

这意味着传递的函数的第一个参数为arg1,其默认值为obj1,依此类推.

This means that the first argument to the passed function is arg1 and it has a default value of obj1, and so on.

这是麻烦:如果它没有默认值,则需要一个占位符值来表示.我不能使用None,因为那样我就无法区分没有默认值默认值为None .对于False,0,-1等也是如此.我可以使它成为具有单个元素的元组,但是用于检查它的代码将很难看,而且我不能轻易地将其变成字典.所以我想我会创建一个类似None的对象,它不是None,而这正是我想出的:

Here's the rub: if it has no default value, I need a placeholder value to signify this. I can't use None, because then I can't distinguish between no default value and default value is None. Same for False, 0, -1, etc. I could make it a tuple with a single element, but then the code for checking it would be ugly, and I can't easily turn it into a dict. So I thought I'd create a None-like object that isn't None, and this is what I've come up with:

class MetaNoDefault(type):
    def __repr__(cls):
        return cls.__name__
    __str__ = __repr__

class NoDefault(object):
    __metaclass__ = MetaNoDefault

现在("arg1", NoDefault)表示arg1没有默认值,我可以执行if obj1 is NoDefault:等操作.元类使它仅显示为NoDefault而不是<class '__main__.NoDefault'>.

Now ("arg1", NoDefault) indicates arg1 has no default value, and I can do things like if obj1 is NoDefault: etc. The metaclass makes it print as just NoDefault instead of <class '__main__.NoDefault'>.

有什么理由不这样做吗?有更好的解决方案吗?

Is there any reason not to do it like this? Is there a better solution?

推荐答案

我最喜欢的哨兵是Ellipsis,如果可以的话

My favourite sentinel is Ellipsis, and if I may quote myself:

它在那里,它是一个对象,它是一个单例,其名称表示缺乏",并且不是过度使用的None(可以作为常规数据流的一部分放入队列中). YMMV.

it's there, it's an object, it's a singleton, and its name means "lack of", and it's not the overused None (which could be put in a queue as part of normal data flow). YMMV.

这篇关于自定义占位符,如python中的None的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆