Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
193 views
in Technique[技术] by (71.8m points)

metaclass - Custom placeholder like None in python

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), ...)

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

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...