English 中文(简体)
in protocol with regard to sequence
原标题:

How is this implemented at a python level?

I ve got an object that pretends to be a dict for the most part (in retrospect I should have just subclassed dict, but I d rather not refactor the codebase, and I d also like to know this for future reference), which looks something a bit like

class configThinger(object):
    _config = {}
    def __getitem__(self, key):
        return self._config[key]
    def __setitem__(self, key, value):
        self._config[key] = value

Which works exactly as it s supposed to and behaves correctly when I try to access it s elements as configThingerInstance[ whatever ]

But a call like

t = configThinger()
t.populate() # Internal method that fills it with some useful data
if  DEBUG  in t:
    doStuff()

results in a KeyError being raised because presumably the `in protocol does a getitem() lookup for the key in question. Do I need to raise some other exception to tell in that it s not there? I d rather not do something like this.

try:
    t[ DEBUG ]
except KeyError:
    pass
else:
    doStuff()

Also, where in the documentation is this?

I was looking around

http://docs.python.org/tutorial/datastructures.html

http://docs.python.org/library/stdtypes.html

but tragically trying to google for something specific to the word in is folly :(

EDIT 1:

With a stack of trace prints, I can see that the program calls configThingerInstance.getitem(0)

however

t = { rawk : 1,
      rawr : 2,
    }
t[0] # Raises KeyError
 thing  in t # returns False
最佳回答

It sounds like you want to overload the in operator?

You can do that by defining the method __contains__: http://docs.python.org/reference/datamodel.html#object.contains

问题回答

For the best support for the in operator (containment aka membership checking), implement the __contains__ special method on your configThinger class:

class configThinger(object):
    _config = {}
    def __getitem__(self, key):
        return self._config[key]
    def __setitem__(self, key, value):
        self._config[key] = value
    def __contains__(self, key):
        return key in self._config

the docs are here (also explaining other, lesser ways to support the in operator).





相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签