[C++-sig] Returning None from __getitem__

Renji Panicker renjipanicker at gmail.com
Fri Sep 19 12:35:14 CEST 2008


Hi all,

I am using boost.python to wrap a map class. My get function looks
like this (edited):

std::map<std::wstring, std::wstring> _values;

class PropSet
{
    std::wstring get(const std::wstring& key)
    {
        if(_values.find(key) == _values.end())
            throw InvalidKeyException();
        return _values[key];
    }
};

In my python code, I would like to be able to do this:
if ps["ssl"] == "yes":
     print "ssl enabled"

My requirement in brief is, if the key 'ssl' exists in the map, and
its value is 'yes', turn on SSL. If the key does not exist, or has any
value other than 'yes', do not turn SSL on. To that extent, I would
like to return None from the get function if the key does not exist,
instead of throwing an exception.

My obvious workaround is to use an empty string, but I am expecting
use cases where the empty string can be a valid value for a key. So I
will have to consider using some other string which cannot be a
potential value, to indicate an empty value. But before I go with this
workaround, I would like to know if there is any standard way of
achieving this.

Thanks in advance.
-/renji



More information about the Cplusplus-sig mailing list