SmartMaps In Scripting

So, I saw a reply (@pturmel’s reply, specifically) to a post that shows a SmartMap implementation. I’m not super familiar with Jython particularities. Do normal Jython dictionaries have some weird implementation that is worth fixing in the scripting world, and have I completely missed the use case for this? I feel like I’m missing something obvious, but I’m also a Java programmer coming to Jython, so there’s still Python oddities I’m figuring out.

The SmartMap class (found here) exposes dictionary keys as attribute names, so that someMap['key'] is equally accessible as someMap.key. Both for assignment and retrieval.

Excluding special attributes names starting with _ and pre-defined dictionary method names, like items().

Unfortunately, it can never be serialized, so I've largely replaced it with the VarMap class from my Integration Toolkit.

{Very similar to Perspective's ObjectWrapper, but usable everywhere.}

2 Likes

Ah, ok. I thought I was missing something, but this is one of the oddities I know about in Jython, I think. It’s something like half the byte code to access a Jython attribute than go through the normal python routes (whether dict access or get/set function calls), so this would be more performant, right?

Attribute access isn't necessarily fewer opcodes. My original intent was to make code more readable.

But attribute access implemented in java (via VarMap) is a huge win over SmartMap's override of __getattr__.

Oh, ok. I conflated SmartMap and VarMap in that case. Code readability is always a win, nonetheless. Thank you for your explanation

The one optimization that I always try to use in jython is the replacement of java .getSomething() with .something, as that eliminates the function invocation opcode.

Yeah, that’s the pattern I had recognized, going from a function to attributes, but dictionary[‘Something’] doesn’t go through a function in the same way that .getSomething() does, so I went too far of a logical leap in my assumption that it must be more performant.