Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hook type casting to dict in Python

In a nutshell I have a class Session inherited from dict (in fact, this class overrides flask.SecureCookieSession class). Also I have a client code that's doing something like this:

session_data = dict(session)

And I want to somehow hook this to dict conversion in order to inject few lines of code modifying session data before serializing. How can I do it in Python?

UPD: To clarify: I don't want to return anything different from a dict object from the dict() call. I just want this call invokes a special method of my session object before getting a data to convert it to the dict object. Something like __to_dict(self) hook.

like image 254
Ivan Velichko Avatar asked Aug 10 '26 01:08

Ivan Velichko


1 Answers

If we look at the source code for dict we can see that when dict is called with a dict subclass, no user methods are called:

int
PyDict_Merge(PyObject *a, PyObject *b, int override)
{
    /* ... */
    if (PyDict_Check(b)) {
        other = (PyDictObject*)b;
        /* ...
           Only other->ma_keys and other->ma_values are used.
           No user-defined methods/attributes are accessed.
           ...
         */
    }
    /* ... */
}

This is a CPython-specific performance optimization.

In order to be able to detect when your dictionary is being copied, you should avoid inheriting from dict and instead provide a mapping-like object. Consider inheriting from MutableMapping or UserDict.

like image 72
Andrea Corbellini Avatar answered Aug 12 '26 15:08

Andrea Corbellini



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!