Help me pick an API design (OO vs functional)

Ethan Furman ethan at stoneleaf.us
Tue Mar 26 00:11:34 CET 2013


On 03/25/2013 12:29 PM, Michael Herrmann wrote:
> Hello everyone,
>
> my name is Michael, I'm the lead developer of a Python GUI automation library for Windows called Automa: http://www.getautoma.com. We want to add some features to our library but are unsure how to best expose them via our API. It would be extremely helpful for us if you could let us know which API design feels "right" to you.
>
> Our API already offers very simple commands for automating the GUI of a Windows computer. For example:
>
> 	from automa.api import *
> 	start("Notepad")
> 	write("Hello World!")
> 	press(CTRL + 's')
> 	write("test.txt", into="File name")
> 	click("Save")
> 	click("Close")
>
> When you execute this script, Automa starts Notepad and simulates key strokes, mouse movements and clicks to perform the required commands. At the moment, each action is performed in the currently active window.
>
> We do not (yet) have a functionality that allows you to explicitly switch to a specific window. Such a functionality would for instance make it possible to open two Notepad windows using the start(...) command, and copy text between them.
>
> One API design would be to have our start(...) function return a "Window" (say) object, whose methods allow you to do the same operations as the global functions write(...), press(...), click(...) etc., but in the respective window. In this design, the example of operating two Notepad windows could be written as
>
> 	notepad_1 = start("Notepad")
> 	notepad_2 = start("Notepad")
> 	notepad_1.write("Hello World!")
> 	notepad_1.press(CTRL + 'a', CTRL + 'c')
> 	notepad_2.press(CTRL + 'v')

This is the way to go.  Just move your global functions into the Window object (or whatever you call it), break 
backwards compatibility (major version number change, perhaps?), and call it good.

It makes much more sense to call methods of several different objects (which is explicit -- you always know which object 
is being used) than having a magic function that changes the object in the background (plus you now have to search 
backwards for the last magic invocation to know -- and what if a called function changes it?).

--
~Ethan~



More information about the Python-list mailing list