Popping key causes dict derived from object to revert to object

dieter.maurer at online.de dieter.maurer at online.de
Thu Mar 21 12:21:52 EDT 2024


Loris Bennett wrote at 2024-3-21 10:56 +0100:
> ...
>So as I understand it, I need to convert the InstanceState-objects to,
>say, dicts, in order to print them.  However I also want to remove one
>of the keys from the output and assumed I could just pop it off each
>event dict, thus:
>
>    event_dicts = [vars(e) for e in events]
>    print(type(event_dicts[0]))
>    event_dicts = [e.pop('_sa_instance_state', None) for e in event_dicts]
>    print(type(event_dicts[0]))
>
>However, this prints
>
>  <class 'dict'>

`vars` typically returns a `dict`.

>  <class 'sqlalchemy.orm.state.InstanceState'>
This is what you have popped.
>
>If I comment out the third line, which pops the unwanted key, I get
Then you do not change `event_dicts`.

You problem likely is:
`pop` does not return the `dict` after the removal of a key
but the removed value.


More information about the Python-list mailing list