Saturday, 30 April 2022

Python Bound Methods Part - 2

This post is a follow-up to this one. There I talked about how invoking a method through an instance of a class will search for that method in the class dictionary and return a bound method, that is, the method with the instance object bound to it, so that it will be passed as first parameter (what we usually call "self"). We'll see now some related details.

In python we have 2 options when declaring a method that does not use an instance of the class (has no "self), what in most languages we call static or class methods:
the @staticmethod decorator and the @classmethod decorator.
In both cases the method can be invoked through the class itself or an instance of that class, I mean MyClass.method() or my_instance.method().

The difference comes from whether the method needs to invoke other methods (classmethods or staticmethods) in the class. In the first case, you have to declare the method as a classmethod, so that it will receive as first parameter the class it belongs to. In the second case you declare it as staticmethod, and you will only receive the parameters that you have passed in the invocation.

My understanding of how classmethods invocation happens is like this. When invoking it through an instance, the lookup mechanism will search the method first (to not avail) in the instance.__dict__ , and then will search it (and find it) in the class.__dict__. Obviously, when invoked through the class, it'll directly search in the class.__dict__. Then, as the method has been decorated with @classmethod, a bound method object will be created (bound to the class) and returned (something like: bound method Person.sayHi of class '__main__.Person'). So when a method is retrieved from a class dictionary, if it's a @classmethod we get it bound to the class, if it's a @staticmethod we get it unbound, and if it's an instance method we get it bound to that instance if accessed through an instance, or unbound if accessed through the class. I mean:


class Person:
    PLANET = "Earth"
    def __init__(self, name):
        self.name = name
    
    def say_hi(self):
        print(f"Person {self.name} says hi")

    @classmethod
    def cls_meth(cls):
        print(cls.PLANET)

    @staticmethod
    def static_meth(msg):
        print(f"msg: {msg}")


p1 = Person("Francois")
print(Person.cls_meth) # bound method Person.cls_meth of class '__main__.Person'
print(p1.cls_meth) # bound method Person.cls_meth of class '__main__.Person'

print(Person.static_meth) # function Person.static_meth at 0x7f2bdddfd040
print((p1.static_meth)) # function Person.static_meth at 0x7f2bdddfd040

print(Person.say_hi) # function Person.say_hi at 0x7f2bdddf4ee0
print(p1.say_hi) # bound method Person.say_hi of __main__.Person object at 0x7f2bdde97730

As I've said, if we retrieve an instance method through the class rather than through an instance we get an unbound method. That unbound method is expecting to receive a "self", so we'll have to pass it along with the other parameters. We could pass an instance of a different class in that "self" (and thanks to duck typing if it has the properties expected by that method it will work).


class Book:
    def __init__(self, name):
        self.name = name

b1 = Book("Guerilla")
Person.say_hi(a1)

# "Person Guerilla says hi

We can do the same in JavaScript (using Array methods with "array like" objects like arguments easily comes to mind), but it's a bit more verbose, e.g:
Array.prototype.slice.call(arguments, 3);

Sunday, 10 April 2022

Your Iterator is also an Iterable

I already explained in this previous post that generators in JavaScript and Python work in a very similar way (a generator function creates a generator object, that is both an iterable and a iterator).

Most times, for Iterable objects that have not been created with a generator fuction (hence, are not generator objects), the Iterator that we obtain from them is a different object, and we can create different iterators over the same iterable and iterate independently. What is pretty interesting is that Python's iteration protocol dictates that iterators have to be iterables also. That means that calling iter() passing on an iterator will return that iterator. From here:

The strangest fact about iterators is that they are also iterables.
When you pass an iterator to the iter function it'll return itself back

JavaScript iteration protocol is less demanding, as it does not require iterators to be iterable. However, I've recently learned here that all ES6 built-in iterators follow the python approach, so they are iterables with a [Symbol.iterator] method that returns the iterator:


[Symbol.iterator]() {
    return this;
}

An example:


> let ar = ["a", "b"];
undefined
> let iterator = ar[Symbol.iterator]();
undefined
> let iterator2 = iterator[Symbol.iterator]();
undefined
> iterator === iterator2;
true

Another interesting thing that I've recently learnt, this time in Python, is that the file object (I tend to call it file-handle) obtained when opening a a file in read mode is both and iterable and an iterator (so it's as if it had been created by a generator function)


>>> fh = open("commands.txt", "r")
>>> fh is iter(fh)
True

Sunday, 3 April 2022

The Hamidian Massacres

I have a profound affection for the Armenian people. It comes down to a long time ago when I first knew about the Armenian Genocide of the early XX century. Over the years this feeling has not done but to increase. Since the day I admitted that regardless of not being a believer and still considering that there are some dubious elements in Christianity, I belong to a civilization deeply shaped by Christianity, a civilization I'm proud of, the story of resistence and survival of this people feels deeply inspiring to me. A Christian nation (the first one) partially surrounded by the eternal enemy of the Western world, Turkey (Azerbijan is populated by the same Turkish people and hence it's just the same enemy).

When many Armenians had to flee their land to avoid being completely annihilated by the Turks in 1917, many of them arrived to Marseille and settled in France. Since them, they have been an important contributor to France. They embraced the French culture and assimilated into the French nation, a nation defined by culture, values and the acceptance of being the continuation of the history that defined all that, not by genes or phenotypes. It's the same that most Polish, Portuguese, Italians, Spaniards, East Asians... and some Africans have done. At the same time, they have kept the links with the land of their ancestors and the pride of descending from a people of survivors.

In spite of the important contributions of the Armenian diaspora in countries like the USA and France, being a small country means being left apart in the Geopolitical game. That's why when Turkey-Azerbaijan invaded Armenian territory in october 2020, slaughtering the population helped by their ISIS mercenaries, nobody seemed to care. Moreover, we all know that when Muslims kill Christians (or atheists, or yazidis, or whatever), reacting to that is a clear sign (and sin) of Islamophobia... Also, when Turkish ultra-nationalists living in France attack French people of Armenian descent, that's not a big deal either... after all that's part of their culture and we have to respect it, right?

With the above and with the fact that many countries (among them Spain and UK!!!!) have not recognized yet the Armenian Genocide, it's not strange that previous massacres perpetrated by the Turks against the Armenians are hardly known. Indeed, I have to admit that I did not know about it until recently, when I watched this excellent video in Le Figaro (it tries to explain why the Turkish-Azeri invasion of Armenia did not prompt the same reactions as the Russian invasion of Ukraine).

So already at the end of the XIX century, the Turks, guided by ultra-nationalism and Islamism (as usual) decided to massacre quite a few thousands (between 100.000 and 300.000) Armenians during the Hamidian Massacres. As they would do 20 years later, they turned their hatred into pure anti-Christian violence, killing an additional 25.000 Assyrians (seems this time the Greeks were excluded, the Turkish would wait 2 decades to show their feelings of "respect, love and peace" to them, during the Greek Genocide). I have not much to say about this unknown massacres, just read the wikipedia article and remember it each time the neo-sultan Erdogan threatens us with his desire to join the European Union (to further destroy us from inside).

Saturday, 26 March 2022

Self-Referencing function in JavaScript

Long time ago it was possible for a function in JavaScript to reference itself by means of arguments.callee. As you can read here, this is not allowed in strict mode and should be avoided in general. You can read in that same url the explanation of why arguments.callee is no longer considered necessary. OK, I agree for the most part, but I still think that there are situations where a function should be able to reference itself in some way.

The obvious case is when you want to print in your logs the function name without hardcoding that function name (either the string or the "function.name" access). Also, in recursive functions it can be useful to call the function using a self-reference rather than the function name. Let's see an example


function recursivePrint(txt, times){
    if (times > 0){
        console.log(`v1: ${txt}`);
        recursivePrint(txt, --times);
    }
    else{
        console.log("------------");
    }
}

recursivePrint("Francoisi", 3);


p1 = recursivePrint;
p1("Francois", 3);
// v1: Francois
// v1: Francois
// v1: Francois
// ------------



//modify recursivePrint to print v2
recursivePrint = function (txt, times) {
    if (times > 0){
        console.log(`v2: ${txt}`);
        recursivePrint(txt, --times);
    }
    else{
        console.log("------------");
    }

};

p1("Francois", 3);
// v1: Francois
// v2: Francois
// v2: Francois
// ------------


In the above example p1 references to recursivePrint. Then we redefine recursivePrint. p1 continues to point to the initial recursivePrint, but in the recursion, as we are calling the function through the global reference, the ensuing calls use the redefined function. So we have a mix of v1 and v2.

Another use for self-referencing functions is if we want to attach data to the function as properties in the function, and use them from inside the function. It's similar to having a closure, in both cases we have a function with state, the main difference is that in a closure accessing to that state from outside is not possible (unless you use some odd technique like the one that that I describe here). So, I'm talking about this:


function formatter(txt){
    console.log(`v1: ${formatter.pre}txt${formatter.post}`);
}
formatter.pre = "[";
formatter.post = "]";

f = formatter;
f("hi");
//v1: [txt]
formatter = (txt) => {
    console.log(`v2: ${formatter.char}txt${formatter.char}`);
}
formatter.char = "|"

//It's a mess here, we continue to point to the original function, but it tries to get the state from the new function
f("hi");
//v1: undefinedtxtundefined

A solution for me would be having a variable inside the function that points to the function itself. We could use the name self for that variable. We can use closures for that, something like this:


function createSelfReferencingFormatterFunction(){
    let self = function formatter(txt){
        console.log(`my name is: ${self.name}`);
        console.log(`${self.pre}txt${self.post}`);
    };
    return self;
}

let formatter = createSelfReferencingFormatterFunction();
formatter.pre = "[";
formatter.post = "]";
formatter("hi");

// my name is: formatter
// [txt]

That looks pretty nice to me, but having to define a factory function for each function that we want to do self-referencing is not nice. How could we generalize it to have a generic function that receives a function and returns a self-referencing funtion?

I've come up with a solution that leverages the unfamous eval function. You can check this post from some years ago where I explain how eval has access to the scope of the function where it's invoked, in such a way that if we define a new function in the string passed to eval, that new function adds that scope to its scope chain.




function createSelfReferencingFunction(fn){
    //we have to use var, not let
    code = "var self = " + fn.toString() + ";"
    eval(code);
    return self;
}

function formatter2(txt){
    console.log(`my name is: ${self.name}`);
    console.log(`${self.pre}txt${self.post}`);
}

f1 = createSelfReferencingFunction(formatter2);
f1.pre = "[";
f1.post = "]";
f1("hi");

// my name is: formatter2
// [txt] 

Notice the comment in createSelfReferencingFunction where I indicate that let does not work and we have to use var. The reason for this is that eval creates a block, so the scope of let is restricted to that block, while var's scope is the whole function. There's an answer in stackoverflow explaining it.

Because eval introduces a new block of code. The declaration using var will declare a variable outside of this block of code, since var declares a variable in the function scope.

let, on the other hand, declares a variable in a block scope. So, your b variable will only be visible in your eval block. It's not visible in your function's scope.

Sunday, 20 March 2022

Python Strictness

I really like JavaScript and Python a lot, both being so profoundly dynamic, and very similar in many aspects, but there are some points where Python is a bit "strict" when compared to JavaScript, and you have to be more careful, let me explain.

Access to non existing items
In JavaScript, access to an index beyond the array length, or to a non existing key in an object or a map, just returns undefined


> let ar = [];
undefined
> ar[2];
undefined

> let ob = {name: "Francois"}
undefined
> ob.city;
undefined


> let m = new Map();
undefined
> m.set("a", "aa");

> m.get("b");
undefined


In python we have to be much more careful, as that kind of access will throw exceptions. So we'll have to check for the array length, the existence of a field via the hasattr() function, and the existence of a dictionary key via "if key in dict" (the has_key() function is deprecated)


>>> ar = []
>>> ar[1]
Traceback (most recent call last):
  File "", line 1, in 
IndexError: list index out of range

>>> d1 = {"name": "Francois"}
>>> d1["city"]
Traceback (most recent call last):
  File "", line 1, in 
KeyError: 'city'

>>> if "city" in d1:
...     print("key exists")
... else:
...     print("key does not exist")
key does not exist

>>> class Person:
...     pass
... 
>>> p1 = Person()
>>> p1.name
Traceback (most recent call last):
  File "", line 1, in 
AttributeError: 'Person' object has no attribute 'name'

>>> hasattr(p1,"name")
False
>>> 


Function parameters/arguments

In JavaScript you can invoke a function with whatever arguments you want, regardless of the parameters defined in the function signature (obviously, the function code will work or not depending on how those arguments are used)


> function fn(a, b){}
undefined
> fn();
undefined
> fn(1,2,3);
undefined


In python you have call the function with a number of arguments that matches the parameters defined in the function (save if you've defined them as *args, **kwargs)


>>> def fn(a,b):
...     pass
... 
>>> fn()
Traceback (most recent call last):
  File "", line 1, in 
TypeError: fn() missing 2 required positional arguments: 'a' and 'b'
>>> fn(1,2,3)
Traceback (most recent call last):
  File "", line 1, in 
TypeError: fn() takes 2 positional arguments but 3 were given
>>> 


strings and null/None
In JavaScript you can print (console.log) a null or undefined value, same as in Python you can print None. But in Python you have to be careful when using "+" for string concatenation (but well, most likely you're using f-strings, right?)


>>> a = "Hi"
>>> b = None

>>> st = a + b
Traceback (most recent call last):
  File "", line 1, in 
TypeError: can only concatenate str (not "NoneType") to str


>>> st = f"{a} - {b}"
>>> st
'Hi - None'

Sunday, 6 March 2022

The Reports on Sarah and Saleem

The Israeli-Palestinian conflict is a difficult topic. It's a mess on which my position has fluctuated a bit over the years, but in a greater or lesser degree I've always been quite supportive of normal Israli people that just want to have a state (of course I profoundly distaste orthodox jews and new settlers) and though I have never cared too much about Palestinians (because of Hamas and even worse groups, because of how Palestinian groups were crucial to unleash the bloody Lebanese civil war). That said, I think for sure that Palestinians deserve to have their own state, particularly the ones living in Cisjordania, and I think Israel, as a wealthy country would have to help a normal Palestinian state (one state that should annihilate the Islamist groups) to develop (a way of paying for the land they've taken from them).

Quite often one can find some form of beauty in pain and madness, and we could say that's the case here. All the suffering caused by this conflict has given us some of the best films ever produced: Le fils de l'autre, Capharnaum and Incendies (as I've said, without the Palestinian conflict probably we would have never witnessed the Lebanese Civil war), and now The Reports on Sarah and Saleem.

I've recently watched this excellent film on TVE2. If you watch it you'll probably wonder how could someone come up with such a crazy story, and well, reallity did, as the film seems to be based on real facts.

We have a married Israeli woman (married to an army high rank) and a married Palestinian guy that are having an affair. When you add to this unfrequent (I guess) situation something that could seem harmless, taking a drink together in Bethlehem (Belén), where nobody knows her, you're setting the ground for some crazy developments. In the end the guy ends up accused of seducing her (the wife of a soldier) to gain knowldge about Israeli military actions. The adulterous man becomes an imprisoned hero for Palestinians, and she becomes a traitor, not just to her husband, but to her nation.

It's really good for me to watch films like this, not just because of how instructive and entertaining they are, but because they remind me that not all Palestinians are crazy Hamas islamists. Many of them are normal guys that undergoing a brutally unfair and harsh existence, try to get by, and try to enjoy life, taking a drink, a dance and flirting with girls (event with Israeli ones).

One of the sequences in this film that I think I'll particularly remember in the future is this dialog between the desperate Israli woman and her work colleague, another young, normal, Israeli woman (I mean that she does not look like a religious or nationalist fanatic). I'm not reproducing the original dialog, just the main sense of what they say:

  • It's horrible, I've cheated on my husband
  • Oh, pour girl. Well, it's not that bad, these things sometimes happen
  • But furthermore he (my lover) is a Palestinian
  • What!!?? You are crazy. There are millions of Jewish men in this world and you have an affair with an Arab! How desperate you are!!!

Probably I would have said those same "racists" (yes, "Arabs" are not a race, but you understand) words. I admit that because of the conflict betwen our civilization and that other civilization, sometimes I tend to generalize and consider almost all Arabs, all Maghrebians and all Turks as our enemies. I know this is unfair, I know not all of them are crazy Islamists, crazy nationalists or crazy criminals, but it's easy to generalize, and when I do so, I'm ashamed about it.

Sunday, 20 February 2022

itertools.tee implemented in JavaScript

Generator functions and Generator objects, iterators and iterables work in a quite similar way in Pyhton and JavaScript, though there are some differences that maybe I will address in a separate post. Both in JavaScript and Python generator functions return generator objects that are both iterables and iterators (so the generator object iterates itself). Because of this, you can iterate a generator object only once. Notice that I explained time ago that this works differently in C#.

Looking into the functionality provided by the Python itertools module I came across an intereting function, tee, that allows creating multiple independent iterators over the same iterable. These iterators point to a buffer around the original iterator. It's a nice idea and I've implemented it in JavaScript



function tee(iterable, num){
    let internalIterator = iterable[Symbol.iterator]();
    let buffer = [];

    //it's very interesting that a generator function can trap the outer variables in a closure, though
    //in the end what is being generated by the compiler is an object with a next() method, not a function that traps the activation object
    function* generatorFn(){
        let pos = 0;
        let finished = false;
        while (!finished){
            if (pos %lt; buffer.length){
                yield buffer[pos];
            }
            else{
                it = internalIterator.next();
                if (it.done){
                    finished = true;
                }
                else{
                    buffer.push(it.value);
                    yield it.value;
                }
            }
            pos++;
        }
    };
    
    let generatorObjs = []
    for (let i=0; i%lt;num; i++){
        generatorObjs.push(generatorFn());
    }
    return generatorObjs;
}


let generatorObj = (function*(){
    yield "a";
    yield "b";
    yield "c";
})()

let [iter1, iter2, iter3, iter4] = tee(generatorObj, 4);

console.log(iter1.next().value);

console.log(iter2.next().value);
console.log(iter2.next().value);
console.log(iter2.next().value);
console.log(iter2.next().value);

console.log(iter1.next().value);
console.log(iter1.next().value);
console.log(iter1.next().value);
for (it of iter3){
    console.log(it);
}

for (it of iter4){
    console.log(it);
}
/*
a
a
b
c
undefined
b
c
undefined
a
b
c
a
b
c
*/

After coding it (and uploading it to a gist) I realized of how the generators and closures machinery is even more impressive than I already knew. In the above code we have a generator function that captures in a closure the "internalIterator" and "buffer" variables in its lexical scope (well, it'll get them through the [[scope]] property...). The amazing thing is that as we know that "generator function" will create "generator objects" on which we will invoke the .next() method, and is really that .next() method who will be accessing the captured variables, so somehow the compiler has to translate the "closure behaviour" (that in this case is a sort of "virtual closure") to a normal object, adding I guess references to the trapped variables to each of the generator objects that it creates. Evenly impressive is the fact that the node.js debugger will show us everything at runtime as if we were just dealing with a normal closure.