|
|
Subscribe / Log in / New account

Python dictionary "addition" and "subtraction"

Python dictionary "addition" and "subtraction"

Posted Mar 13, 2019 17:17 UTC (Wed) by smurf (subscriber, #17840)
In reply to: Python dictionary "addition" and "subtraction" by pj
Parent article: Python dictionary "addition" and "subtraction"

You can create a subclass of "dict" with extra methods, but you can't do that on "dict" directly. Built-in types are immutable. If you want a language you can do this with, use Ruby.


to post comments

Python dictionary "addition" and "subtraction"

Posted Mar 13, 2019 19:26 UTC (Wed) by ms-tg (subscriber, #89231) [Link] (1 responses)

> You can create a subclass of "dict" with extra methods, but you can't do that on "dict" directly. Built-in types are immutable. If you want a language you can do this with, use *Ruby*.

Definitely!

In fact, Ruby provides a way to do it *without monkey-patching* called Refinements:
https://ruby-doc.org/core-2.5.3/doc/syntax/refinements_rd...

So if you wanted to extend the Ruby Hash class (equivalent to Python Dict) in this way with method #+ and #+=, you could create the following refinement module:

module HashWithPlus
refine Hash do
alias_method :+, :merge
alias_method :"+=", :merge!
end
end

Then, in any lexical scope you can say:

using HashWithPlus

{ "a" => 1 } + { "b" => 2}
=> {"a"=>1, "b"=>2}

With no monkey-patching! The refined Hash will only be visible in scopes that explicitly use the refinement.

(just sharing for those interested)

Python dictionary "addition" and "subtraction"

Posted Mar 14, 2019 10:00 UTC (Thu) by sheepgoesbaaa (guest, #98005) [Link]

Thanks, I enjoyed reading that :)


Copyright © 2025, Eklektix, Inc.
Comments and public postings are copyrighted by their creators.
Linux is a registered trademark of Linus Torvalds