[Pythonmac-SIG] coercing to text (Adam Morris)

has hengist.podd at virgin.net
Tue Dec 15 19:48:12 CET 2009

Adam Morris wrote:

> ASTranslate tells me that
> tell application "Pages" to tell front document to get selection as text
> should be
> app(u'Pages').documents[1].selection.get(resulttype=k.unicode_text)
> but that doesn't return what I want (a reference? ... hardly useful!). Yet:
> app('Pages').documents[1].selection()()
> returns what I want. The unicode text.
> I don't get what that 'extra' set of parens is doing. What implicit function
> is being called? Can't imagine it's get().


is shorthand for:


First command asks for the selection property's value; Pages returns a reference representing a text range. Second command asks for the specified text range, Pages returns the characters in that range as a (Unicode) string.

> I'm obviously missing something here, but no idea what! ASTranslate seems to
> be missing it too. Thanks for your help!

ASTranslate only tells you what events AppleScript sent. In this case, it looks like Pages is completely ignoring the return type argument and always returning a reference (Apple never laid down hard rules about how this feature should work, so different applications do all sorts of different things - though most just ignore it). 

If the value returned by an application command isn't of the type you specified, AppleScript will make its own attempt to correct this by coercing the value itself - and AS resolves coercing a reference by packing it into a 'get' event and sending it off for the application to evaluate. (You won't see that second event in ASTranslate unless the 'send events to app' option is checked.)

Appscript replicates most AppleScript behaviours for sake of application compatibility, but doesn't try to mimic this sort of opaque, non-publicly documented magic (e.g. no implicit gets, no munging of 'count' commands) just because it's tricky to figure out exactly what AS is doing at times, and mimicking it badly is worse than not mimicking it at all. So what you ask appscript for is exactly what you get, and 98% of the time it's what AS would have asked for as well. It's the other 2% of corner cases that are tricky to fathom, but once you understand what's going on it should be straightforward to rephrase your requests appropriately - in this case by sending a second 'get' command yourself.


Control AppleScriptable applications from Python, Ruby and ObjC:

More information about the Pythonmac-SIG mailing list