A new idea of Ruby-like method chain in wx(Python) shell

Hi, there!

I have been using py.shell in my application. Recently I realized that wxPython could implement a Ruby-like method chain and tried it.


Quote: In Ruby, everything is an object. Every bit of information and code can be given their own properties and actions. … Ruby’s pure object-oriented approach is most commonly demonstrated by a bit of code which applies an action to a number. (About Ruby)

irb> 5.times { print "We *love* Ruby -- it's outrageous!" }

Some of them have criticized Python as an inconsistent language. For example, Python uses mix of method and functions like sum((1,2,3,4j)).real. Ugly? No. Rather, I think, it is the flexibility of Python, no inconsistency.


I got an idea to make Python chainable like Ruby. To do that, one and only one quite simple rule was required as follows;

x @ y => y(x)

Hence, we can chain methods as x @y @z => z(y(x)). I named this rule ‘pullback’ which comes from mathematical terminology. Actually, this rule can chain not only the instance method but also ANY functions.

Here shows a simple example:

irb> p 5.times.to_a
[0, 1, 2, 3, 4]
>>> 5 @range @list @p
[0, 1, 2, 3, 4]

Note that the printing function (p = print) is also chained.

In the next example, you will see that methods and functions in any modules are chained. Suppose buf is the binary data received from the image server. The input and output-code are like these:

# input:
>>> buf @io.BytesIO @Image.open @np.asarray @plt.imshow; plt.show()

# interpreted as:
==> plt.imshow(np.asarray(Image.open(io.BytesIO(buf)))); plt.show()

Also, note that you can check if the py expression is correct each time you chain. This is the greatest benefit of Shell being a REPL, not just a text editor. So I have overridden and extended the py.shell, which was the best choice for me to experiment with my idea, the chain rules. it works very well for me more than I expected!

Thank you for reading! :slightly_smiling_face: If you are interested in this idea, please visit my GitHub, and have some try. I also have been reinforcing auto-comp functions, and I hope it will be useful not only for beginners but also for professionals.