<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Martim Nascimento on Medium]]></title>
        <description><![CDATA[Stories by Martim Nascimento on Medium]]></description>
        <link>https://medium.com/@martim00?source=rss-f5d24bf7c855------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*XvKMa1eAnKjHamLAO91rHg.jpeg</url>
            <title>Stories by Martim Nascimento on Medium</title>
            <link>https://medium.com/@martim00?source=rss-f5d24bf7c855------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 06:14:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@martim00/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Python duck typing (or automatic interfaces)]]></title>
            <link>https://medium.com/hackernoon/python-duck-typing-or-automatic-interfaces-73988ec9037f?source=rss-f5d24bf7c855------2</link>
            <guid isPermaLink="false">https://medium.com/p/73988ec9037f</guid>
            <category><![CDATA[automatic-interfaces]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[duck-typing]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python-duck-typing]]></category>
            <dc:creator><![CDATA[Martim Nascimento]]></dc:creator>
            <pubDate>Sat, 30 Sep 2017 20:16:58 GMT</pubDate>
            <atom:updated>2019-05-06T07:30:35.548Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jPeGjUlwLBKovESpYTioHA.jpeg" /></figure><p>Working with <a href="https://hackernoon.com/tagged/python">python</a> full-time now I, more often, have insights about its way of doing things (or <a href="https://www.python.org/dev/peps/pep-0020/">Zen of python</a> for some people). One thing that blows my mind every time I find out in my daily saga is the duck typing thing. Being honest, it is not a python exclusive feature, since almost every dynamic language presents that behavior. But be nice, I like Python.</p><p>If some reader doesn’t know what it is, duck typing is a feature of a type system where the semantics of a class is determined by his ability to respond to some message (method or property). The canonical example (and the reason behind the name) is the <a href="https://en.wikipedia.org/wiki/Duck_test">duck test</a>: <em>If it looks like a duck, swims like a duck, and quacks like a duck, then it probably is a duck.</em></p><pre>class Duck:<br>   def quack():<br>      print(&#39;Quack!&#39;)</pre><pre>class Goose:<br>   def quack():<br>      print(&#39;Quack&#39;)</pre><pre>Goose().quack()<br>&gt;&gt; Quack!</pre><pre>Duck().quack()<br>&gt;&gt; Quack!</pre><p>Ok, but what is the catch? There is nothing new here. Yes, nothing new. What I’m trying to show is the implications that this behavior has in the architecture of a system. And I’m advocating that this is a good implication. Let me explain.</p><p>Imagine a class named <em>Car</em>:</p><pre>class Car:<br>   def __init__(self, engine):<br>      self.engine = engine</pre><pre>   def run():<br>       self.engine.turn_on()</pre><p>This is a classical example of dependency injection. My class <em>Car</em> receives an instance of an engine and use it in the run method, where it calls the <em>turn_on</em> method. Note that my <em>Car</em> does not depends on any concrete implementation of engine. And I&#39;m not importing any other type! Just using a dependency injected instance of something that responds to a <em>turn_on</em> message. I could say my class <em>Car</em> depends on an interface. But I did not have to declare it. It is an automatic interface!</p><p>In a language without duck typing I&#39;ll probably have to declare an explicit interface named for example <em>IEngine</em>, have the implementation (for example <em>EngineV1</em>) and explicit define my <em>Car</em> parameter to be an implementation of <em>IEngine</em>.</p><pre>interface IEngine {<br>    void turnOn();<br>}</pre><pre>public class EngineV1 implements IEngine {<br>    public void turnOn() {<br>        // do something here<br>    }<br>}</pre><pre>public class Car {<br>    public Car(IEngine engine) {<br>       this.engine = engine;<br>    }</pre><pre>    public void run() {<br>        this.engine.turnOn();<br>    }</pre><pre>}</pre><p>Ugh! How much code.</p><p>So, as you can see the effect is the same. My class <em>Car</em> in both cases depends on an interface. But in the first case there are less code and I don&#39;t need to explicit implement the interface. It&#39;s already implemented if I define the method <em>turn_on</em>.</p><h4>The weakness</h4><p>I can see two problems here.</p><ol><li>Fat interface</li></ol><p>The first is an incentive to <a href="https://en.m.wikipedia.org/wiki/Interface_bloat">interface bloat</a>. As we don’t explicit define the API this can result in an interface with too much granular methods.</p><p>2. Unnamed dependencies</p><p>As we don’t know the name of the interfaces that a class depends we don’t have an automatic dependency tree. Because of this, all dependency injection frameworks have to workaround the dependency resolution in some way.</p><p><a href="http://injector.readthedocs.io/en/latest/index.html">Injector lib</a>, for example, was obligated to implement the concept of <a href="http://injector.readthedocs.io/en/latest/terminology.html#keys">Keys</a> to allow dependency tree to be resolved automatically. Keys, in injector terms, are nothing more than a way to name/identify an interface that a class implements.</p><h4>Conclusion</h4><p>I don&#39;t think that duck typing was intentionally designed to have this behavior. I don&#39;t even think that duck typing is intentionally designed in a language at all but instead it is a side-effect of the dynamic nature of those type systems. But it is interesting what it can brings in terms of conciseness and low-coupling to the system <a href="https://hackernoon.com/tagged/design">design</a> and architecture.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fdde502%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2Fhackernoon%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href">https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=73988ec9037f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/python-duck-typing-or-automatic-interfaces-73988ec9037f">Python duck typing (or automatic interfaces)</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Making a webpack python loader]]></title>
            <link>https://medium.com/hackernoon/making-a-webpack-python-loader-87215d72292e?source=rss-f5d24bf7c855------2</link>
            <guid isPermaLink="false">https://medium.com/p/87215d72292e</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[webpack]]></category>
            <dc:creator><![CDATA[Martim Nascimento]]></dc:creator>
            <pubDate>Sat, 23 Sep 2017 14:25:34 GMT</pubDate>
            <atom:updated>2017-09-25T15:54:39.374Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/478/1*e7KVLPIwRD0rNwlXSaQgOQ.png" /></figure><p>For some time I was an observer of initiatives in using python in the browser. A long time ago I was a follower of <a href="http://pyjs.org/">Pyjamas/PyJS</a> project, including watching in real time <a href="https://groups.google.com/d/msg/pyjamas-dev/3NZ0No2hLUw/3i2ynpKv7-IJ">the leadership war between some of its contributors</a>. Now we have a plethora of projects trying to make this a reality (<a href="https://github.com/skulpt/skulpt">1</a>, <a href="http://www.transcrypt.org/">2</a>, <a href="http://www.rapydscript.com/">3</a>, <a href="https://github.com/brython-dev/brython">4</a>, etc) but the workflow, development usability and integration with modern javascript is far from acceptable.</p><p>With the new wave of language <a href="http://composition.al/blog/2017/07/30/what-do-people-mean-when-they-say-transpiler/">transpilers</a> for javascript that dream turned to be possible and almost inevitable. Without knowing the scope of each project I always had the impression that <a href="https://babeljs.io/">BabelJS</a> would be the best place to make that process. But after investigating a little more and have used in some projects I realized that <a href="https://webpack.github.io/">WebPack</a> would be the right way to do that.</p><p>Last week I decided to experiment with this idea. I knew that <a href="https://github.com/pyjs/pyjs">PyJS</a> (old Pyjamas) would not be the best option for the transpilation. After the leadership war the project almost died. <a href="https://github.com/skulpt/skulpt">Skulpt</a> could be a strong choice if it wasn’t restricted to Python 2. The <a href="http://www.transcrypt.org/">Transcrypt</a> project seemed to be appropriated since supports Python 3 and the option for fast code generation (at least is what his slogan says) is a must, so I choose it.</p><p>(Edited: <a href="http://www.rapydscript.com/">RapydScript</a> and <a href="https://github.com/brython-dev/brython">Brython</a> could also be a good choice. I will try those in the future)</p><p>The next step would be implement the webpack loader. For that I have used the webpack documentation as reference (obvious) but also those loaders as example:</p><ul><li><a href="https://github.com/webpack-contrib/coffee-loader">coffee-loader</a></li><li><a href="https://github.com/TypeStrong/ts-loader">ts-loader</a></li><li><a href="https://github.com/QingWei-Li/pue-loader">pue-loader</a></li><li><a href="https://github.com/webpack-contrib/css-loader">css-loader</a></li></ul><p>To implement a webpack loader we need to implement and export a javascript function that receives the original source code (python) and returns the javascript transpiled code as a string. The loader when installed in the webpack.config.js file will join the webpack transformation chain.</p><h3>Async</h3><p>Since we’ll use the node filesystem api to read and write the file we need to use the async webpack loaders api. For that we need just to call the this.async webpack method. This method returns a callback that we need to call when our processing was finished.</p><p>The canonical result is listed here (you can see the complete result in the <a href="https://raw.githubusercontent.com/martim00/python-webpack-loader/master/index.js">repository</a>)</p><pre>const cmd = require(&#39;node-cmd&#39;)<br>const fs = require(&#39;fs&#39;);<br>const path = require(&#39;path&#39;);</pre><pre>module.exports = function (source) {</pre><pre>    var callback = this.async();</pre><pre>    var entry = this._module.resource;</pre><pre>    var name = path.basename(entry, &quot;.py&quot;);</pre><pre>    cmd.get(&#39;transcrypt -b -n &#39; + entry, <br>        function(err, data, stderr) {<br>            if (!err) {<br>            js = fs.readFileSync(<br>                 &quot;./__javascript__/&quot; + name + &quot;.js&quot;, &quot;utf8&quot;)<br>            callback(null, js);<br>        }<br>        else {<br>            console.log(&quot;Error: &quot; + err);<br>        }</pre><pre>    });<br>}</pre><h3>Let’s use it!</h3><p>if someone have interest in helping I published the source code in <a href="https://github.com/martim00/python-webpack-loader">github</a> and uploaded to <a href="https://www.npmjs.com/package/py-loader">npm</a> (py-loader). In the repository there are an example but if you want a quickstart just follow the steps below:</p><ol><li>Install transcrypt (you will need pip)</li></ol><pre>pip install transcrypt</pre><p>2. Install the package</p><pre>npm install --save-dev py-loader</pre><p>3. Add the loader inside your webpack.config.js</p><pre>function cwd (path) {<br>  return require(&#39;path&#39;).resolve(__dirname, path)<br>}</pre><pre>module.exports = {<br>  entry: cwd(&#39;main.js&#39;),</pre><pre>  output: {<br>    path: cwd(&#39;dist&#39;),<br>    filename: &#39;app.js&#39;<br>  },</pre><pre>  module: {<br>    rules: [<br>      {<br>        test: /\.py$/,<br>        loader: &#39;py-loader&#39;<br>      }<br>    ]<br>  }<br>}</pre><p>4. Create a python file named hello.py</p><pre>def hello_world():<br>   print(&quot;Hello from python&quot;)<br>   print(&quot;document {}&quot;.format(document))</pre><p>5. Create a javascript file (main.js) that imports the python file</p><pre>import Hello from &#39;./hello.py&#39;</pre><p>6. Include the generated file in a html</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>  &lt;meta charset=&quot;UTF-8&quot;&gt;<br>  &lt;title&gt;Document&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body onload=&quot;hello.hello_world()&quot;&gt;<br>  &lt;div id=&quot;app&quot;&gt;&lt;/div&gt;<br>  &lt;script src=&quot;app.js&quot;&gt;&lt;/script&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>7. Execute the webpack build process</p><pre>webpack --progress --profile --colors</pre><p>Open the html in the browser. Voilá! You should see the “Hello from python” message in the browser console.</p><p>It also works with webpack-dev-server so you can have the same live-reload experience you have with javascript!</p><pre>webpack-dev-server --progress --colors --port 8080 --content-base .</pre><h3>The future</h3><p>There are still many things to do for making our dream to program Python in the browser (seamless) come true. Below I list some:</p><ol><li>Verify the possibility in Transcrypt to use an in-memory transpilation instead of saving to a temporary file. This could improve the speed of the process.</li><li>Verify the viability in using another javascript libraries (like axios) inside python code.</li><li>Experiment with other python/javascript transpilers (RapydScript and brython are in the queue).</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=87215d72292e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/making-a-webpack-python-loader-87215d72292e">Making a webpack python loader</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>