Friday, 22 July 2022

Run Function with Timeout

I've recently needed to be able to stop a function if it had not finished after a timeout period. I'm not talking about an eventloop and an asynchronous function returning an awaitable in Python (or a Promise in Javascript). Indeed, years ago I already posted about expirable promises in JavaScript. What I'm talking about is a synchronous Python function (normally doing some CPU bound calculation) that we want to stop if it has not finished after a given amount of time. I say stop its operation, not just stop waiting for it but let it run in the background uselessly consuming resources.

A solution that easily comes to mind is running the function in a separate Thread and joining that thread with the timeout option. If the timeout expires our calling code will stop blocking and continue on, but the problem is that the thread doing that costly CPU operation will continue to run and we have no way to kill it. This is something that really bothers me. Neither Python, nor .Net nor Java let you kill a thread "from outside" (I mean from another thread, what is still possible I think is killing the thread you are running in). I know that the reason for discouraging and not providing this functionality is that when you kill another thread it could be holding resources or doing something critical and killing it could mess things...) OK, but we are grown ups, so if you know that such thread can be killed withoug causing problems, you should be allowed... Well, anyway...

In order to overcome the limitations imposed by the GIL to parallelism, python provides an extremely powerful library to run your code in separate processes as easily as you run it in separate threads in other platforms: multiprocessing (and the higher level ProcessPoolExecutor in concurrent.futures). Contrary to threads, you are allowed to kill (terminate) processes, so I've implemented the timeout functionality running the function in a separate process.

So I have a create_func_with_timeout factory function, that receives a function fn and a timeout value and returns a new function that takes care or running fn in a separate process, waiting for it for a timeout time and throwing a TimeoutException if it expires. If fn itself were to throw an exception we want to have it available in the calling process, so to manage this we wrap the execution of fn in the mp_function_wrapper function. This function returns to the calling process the normal result of running fn (or an exception it that were the case) by writing it to a multiprocessing queue.

Reading the code should make it clear:


import multiprocessing
import queue
import threading
from time import sleep
from typing import Any, Dict, TextIO, List, Callable, Tuple, Optional, AnyStr, Match, cast


class TimeoutException(Exception):
    pass

def create_func_with_timeout(fn: Callable, timeout: int) -> Callable:
    """
    returns a new function that runs the provided fn in a separate process that either finishes normally or times out
    """
    def mp_function_wrapper(fn: Callable, queue: multiprocessing.Queue, *args, **kwargs):
        """
        this function has been started in a separate process
        it "returns" the result of fn to the main process by writing it to the queue
		we could take fn and timeout as closure values, but it seems more clear to pass them as parameters
        """
        try:
            result = fn(*args, **kwargs)
        except BaseException as ex:
            result = ex
        queue.put(result)
        
    def func_with_timeout(*args, **kwargs):
        """
        has the fn to run trapped as closure value
        """
        try:
            multiprocessing.set_start_method('fork')
            # multiprocessing.set_start_method('spawn')
        except RuntimeError as ex:
            print(f"set_start_method: {ex}")
        print(f"func_with_timeout {fn.__name__} {timeout}")
        response_queue = multiprocessing.Queue()
        extended_args = [fn, response_queue, *args]
        proc = multiprocessing.Process(target=mp_function_wrapper, args=extended_args, kwargs=kwargs)
        proc.start()
        try:
            result = response_queue.get(block=True, timeout=timeout)
        except queue.Empty:
            # the process is still running, so finish it off
            proc.terminate()
            raise TimeoutException()
        if result and isinstance(result, BaseException):
            raise result
        return result
  
    return func_with_timeout


def format_items(items):
    #print(f"format_items")
    results = []
    for item in items:
        sleep(1)
        results.append(item.upper())
        #print(item)
    return ",".join(results)

format_with_timeout = create_func_with_timeout(format_items, 5)

def run_test(items):
    print("- test")
    try:
        res = format_with_timeout(items)
        print(f"result: {res}")
    except BaseException as ex:
        print(f"exception: {type(ex).__name__} {ex}")


print("- starting")

run_test(["a", "b", "c"])

run_test(["a", "b", "c", "d", "e", "f", "g"])

run_test(["a", None])

print("- ending")

# - starting
# - test
# format_items
# result: A,B,C
# - test
# format_items
# exception: TimeoutException
# - test
# format_items
# exception: AttributeError 'NoneType' object has no attribute 'upper'
# - ending


I've also uploaded it to a gist

Friday, 15 July 2022

Creating classes dynamically

Python classes are profoundly dynamic. We can add new methods to a class or an instance, modify the inheritance chain, switch one method implementation for another one, or dynamically create a new class... Remember from my previous post that classes are instances of the type metaclass or of a custom metaclass.

Given these methods and data attributes that we want in our dynamic class:


# initializer
def init(self, name):
    self.name = name
  
# method
def say_hi(self, to):
    return f"{self.name} says hi to {to}"
  
# class method
@classmethod
def my_class_method(cls, arg):
    return f"{cls.__name__}.{cls.my_class_method.__name__} invoked with arg: {arg}, {cls.class_attribute}"

class_items = {
    # constructor
    "__init__": init,
      
    # class data
    "class_attribute": "AAAA",
      
    # methods
    "say_hi": say_hi,
    "my_class_method": my_class_method
}

def test_dynamic_class(cls):
    p1 = cls("Francois")
    print(p1.say_hi("Antoine"))
    print(cls.my_class_method("BB"))
    print(cls.class_attribute)

We can create a class with type as its metaclass by invoking type like this:


# creating class dynamically
Person = type("Person", (object, ), class_items)

test_dynamic_class(Person)

# Francois says hi to Antoine
# Person.my_class_method invoked with arg: BB, AAAA
# AAAA


An alternative would be creating an "empty" class and adding the methods and data attributes like this:


class Person2:
    pass

for key, value in class_items.items():
    setattr(Person2, key, value)

test_dynamic_class(Person2)

# Francois says hi to Antoine
# Person2.my_class_method invoked with arg: BB, AAAA
# AAAA


If we want to dynamically create a class using a custom metaclass we have to use types.new_class. Notice that rather than passing a dictionary with the attributes, we pass a function that adds those attributes to the "class namespace"


class Meta1(type):
    pass

def fill_namespace(ns):
    ns.update(class_items)

Person3 = types.new_class(
    name="Person3",
    #bases=(B, C),
    kwds={"metaclass": Meta1},
    exec_body=fill_namespace
)

test_dynamic_class(Person3)

# Francois says hi to Antoine
# Person3.my_class_method invoked with arg: BB, AAAA
# AAAA

We can also use the alternative technique of creating an "empty class" (but with our custom metaclass): class Person3(metaclass=Meta1) and then adding the methods and data attributes to it.

Saturday, 9 July 2022

Python Metaclasses

Metaclasses are a very interesting topic. The basic idea is In object-oriented programming, a metaclass is a class whose instances are classes.. That means that basically all Object Oriented languages have metaclasses. In C# all classes are instances of Type, in Java all classes are instances of Class... So the interesting thing comes when we can define custom metaclasses, as we can do for example in Groovy and Python.

I talked about Groovy metaclasses so many years ago. Custom metaclasses in Grooy are frequently used, while that's not the case in Python. The reason for this is that most of the features that require metaclasses in Groovy (expanding and object or class, interception...) are present in python through different means (__getattribute__, __getattr__...)

This means that custom metaclasses are rarelly necessary in Python, but anyway, I find it useful to have an (at least partial) understanding of how they work and their relation with callables and the attribute lookup mechanism.

This is probably the most in depth article I've found about metaclasses. I can not say I've fully understood it... but with it and other readings I think I have the basic idea of how things work. Let's go

type
Classes and functions are objects. object is an instance of type. type is an instance of type and inherits from object. A class is an instance of type. A metaclass is an instance of type and inherits from type. To find the metaclass of a class A, we just do type(A).

Callables
When python comes across this: x() it checks what class x is an instance of, and will call the __call__ method in that class with x as first parameter.

Creation of an Instance of a class
When creating an instance of a class A (a = A()) it invokes its metaclass .__call__ (so for "normal" classes it's type.__call__ and for classes with a custom metaclass it's CustomMetaclass.__call__). Then type.__call__(cls, *args, *kwargs) basically does this: invokes cls.__new__(cls) (that unless overriden is object.__new__) and with the returned instance object it invokes cls.__init__(instance)

Creation of a class
When creating a class A (class A:) it's like doing A = type("A", bases, attributes). So it invokes __call__ in type's metaclass, that happens to be type itself, so type.__call__(type). Then this invokes type.__new__ and type.__init__ (by the way, in case you are wondering whether type.__new__ is just the same as object.__new__, no, they are not)

Custom metaclass
- When creating a class with a custom metaclass (class A(metaclass=MetaB):), we are creating an instance of MetaB, so we end up calling MetaB.__new__ and MetaB.__init____.
- When creating an instance of a class A that has a metaclass MetaB (a = A()), this calls MetaB.__call__ (that could have been overriden in MetaB, or otherwise will be type.__call__)

From all the above, we can get to the 2 main uses of metaclasses:
- Defining __new__ and/or __init__ in the metaclass we can manage how instances of that metaclass (classes) are created. - Defining a custom __call__ method in the metaclass we can manage how instances of classes of that metaclass are created (singleton?).

This article makes a good read about the above. Just to make the signatures clear:


class MyMeta(type):
    def __new__(self,name,base,ns):
        print("meta new")
        return type.__new__(self,name,base,ns)
    def __init__(self,name,base,ns):
        print("meta init") self.cloned = False
        type.__init__(self,name,base,ns) class 

metaclasse and method lookup

Metaclasses do not add extra layers to the attribute lookup mechanism. Let's say we have "class A" and "a = A()". When looking up an attribute at1 in object a (a.at1), python searches first in a's __dict__ (or slots) and if not there, it'll check what class a is an instance of (that is, A), and will search in A's __dict__ and in that of its base classes. It will not use A's metaclass in this lookup mechanims at all.

If we search an attribute in a class (A.att1), python searches first in A.__dict__, then as it sees that is an instance of type (or a derived metaclass) or maybe just because it sees that it has a __bases__ attribute, it checks in the __dict__ of its parents. If not there, as A is an instance of type, it will search in type.__dict__. So yes, in this case it's using the metaclass, but just because it's the first "instance of", but it does not go deeper with the "instance of" of "instance of" of...

metaclasses and inheritance Custom metaclasses are inherited from your base classes. With multiple inheritance it becomes a bit complex, it's perfectly explained in the superb article that I mentioned above.

Immutable
You can not switch the metaclass of a class for a different metaclass once it has been created (and contrary to what some posts say, it makes sense to want to do that, as changing the metaclass of a class can change how instances of the class are created). However, there's an easy workaround, similar to what I do in my previous post. Create a new class that inherits from the one we want to modify and assign it the new metaclass. I mean:


class Meta1(type):
	pass
	
class A(metaclass=Meta1):
	pass

class Meta2(type):
	pass	

# now, let's "change" the metaclass of A from Meta1 to Meta2

class A2(A, metaclass=Meta2):
	pass
	

And then use A2 rather than A for creating new instances. We've previously seen that for already existing instances the metaclass of it's class does not play any role, so not being able to change it does not pose any problem.

Wednesday, 6 July 2022

Intercept instance access

As of lately I've been reviewing some Groovy code, mainly to remember how metaclasses are used in Groovy (they work quite differently from Python). Both instances and classes have a metaclass property, and among other things they can be used to intercept access to a specific instance or to all instances of a class. You can check it here



class InterceptionThroughMetaClassTest extends GroovyTestCase {

    void testPOJOMetaClassInterception() {
        String invoking = 'ha'
        invoking.metaClass.invokeMethod = { String name, Object args ->
            'invoked'
        }

        assert invoking.length() == 'invoked'
        assert invoking.someMethod() == 'invoked'
    }

    void testPOGOMetaClassInterception() {
        Entity entity = new Entity('Hello')
        entity.metaClass.invokeMethod = { String name, Object args ->
            'invoked'
        }

        assert entity.build(new Object()) == 'invoked'
        assert entity.someMethod() == 'invoked'
    }
}


In Python we don't use metaclasses for that. We define a __getattribute__ method (you can check this previous post) in one class and this way we intercept the access to all instances of that class. So. what if we wanted to intercept the access only to one specific instance? Defining __getattribute__ at the instance level won't work.

But given Python's versatility, there's an easy trick to achieve just that. Given an instance that we want to intercept we can create a new class that inherits from that instance's class. Add a __getattribute__ method to that class, and then change the class of the instance from the original class to the derived class that includes the __getattribute__ method. Nice!


# In Groovy we can add interception to an instance (not to a whole class) by means of adding it to the instance metaclass
# we can do something like that in Python by creating a new class that inherits the original class of the instance, and changing the class of the instance
# in that new class we implement __getattribute__

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

    def say_hi(self, person):
        #print("inside say_hi")
        return f"Hi person, I'm {self.name}"


def add_interception_to_instance(obj, interceptor_fn):
    class Interceptor_class(obj.__class__):
        def __getattribute__(self, name):
            interceptor_fn(self, name)
            return object.__getattribute__(self, name)
    obj.__class__ = Interceptor_class

p1 = Person("Xuan")
print(p1.say_hi("Francois"))
# Hi person, I'm Xuan

def logger_interceptor_fn(obj, attr):
    print(f"intercepting access to {attr}")

add_interception_to_instance(p1, logger_interceptor_fn)
print(p1.say_hi("Francois"))
#interception happens:
# intercepting access to say_hi
# intercepting access to name
# Hi person, I'm Xuan
print(isinstance(p1, Person))
# True

# other instances of Person are not intercepted
p2 = Person("Iyan")
print(p2.say_hi("Francois"))
# Hi person, I'm Iyan

I've uploaded it to a gist

Thursday, 30 June 2022

Create Child Instance from Parent Instance

Recently I was thinking for a while about how better design this case (in python). I have a Base class and a Child class and I want to create a Child instance from an existing Base instance. I ended up with this design


import json

class City:
    def __init__(self, name, population):
        self.name = name
        self.population = population
        self.neighbourhoods = []

    def add_neighbourhood(self, name):
        self.neighbourhoods.append(name)

class FrenchCity(City):
    def __init__(self, name, population, urban_area_population):
        super().__init__(name, population)
        self._initialize(urban_area_population)

    def _initialize(self, urban_area_population):
        self.urban_area_population = urban_area_population
        self.related_cities = []

    def add_related_city(self, city):
        self.related_cities.append(city)

    @classmethod
    def create_from_city(cls, city, urban_area_population):
        # I'm doing object.__new__ rather than calling FrenchCity constructor cause in other classes 
        french_city = object.__new__(cls)
        french_city.__dict__.update(city.__dict__)
        french_city._initialize(urban_area_population)
        return french_city


city = City("Paris", 2000000)
city.add_neighbourhood("Belleville")
f_city = FrenchCity.create_from_city(city, 12000000)
f_city.add_related_city("Saint Mande")
print(json.dumps(f_city, indent=4, default=lambda x: x.__dict__))

So as you can see I have added a create_from_[parent] static method to the child class. In it I assign the data in the parent instance __dict__ to the child instance __dict__. Yes, I know that direct access to __dict__ should be avoided as it's mainly an implementation detail, but at the same time it's well known and I don't think it's going to change in the near future.

The other interesting part in the create method is that rather than invoking the child constructor, I'm calling object.__new__ (that's also why I've split the initialization functionality between the normal __init__ method and an _initialize method) rather than the normal Child "constructor" (that ends up calling both __new__ and __init__). In this particular class I could use that "constructor" cause it's clear what parameters to pass from the parent instance fields, but this is not always the case, so the generic way is to create an instance of the child class using __new__, then initialize the child properties with an _initialize method (that we also use when creating the instance from scratch rather than from an existing parent instance), and then set the properties from the parent instance using __dict__

There's a gotcha. We could have a class that were using __slots__ rather than __dict__. Adapting to that should not be a big deal, but I would have to review how __slots__ work.

Saturday, 18 June 2022

Measuring Time

In some recent script at some point I wanted to measure the time consumed in different sections of code (in a basic manner, it's not profiling information to store somewhere or anything, just to print on screen and probably end up removing it). I ended up with this:


start = time.time()
# do things
print(time.time()-start)
start = time.time()
# do something
print(time.time()-start)
start = time.time()
# do something
print(time.time()-start)
start = time.time()

Those 2 lines for each time I want to print and start the next "snapshot" add quite a bit of noise to the code. Oddly, I did not find an immediate, ready-made solution for this. so I came up with a nice use for a generator. We can have a generator function like this:


def elapsed_generator_fn():
    start = time.time()
    yield # we need a first next() call to perform this initialization
    while True:
        now = time.time()
        elapsed = now - start
        start = now
        yield elapsed

And write our code this way:


    elapsed = elapsed_generator_fn()
    # init it
    next(elapsed)

	# do something
    print(f"elapsed: {next(elapsed)}")

	# do something
    print(f"elapsed: {next(elapsed)}")

	# do something
    print(f"elapsed: {next(elapsed)}")


In the above code the first next() call is for initialization (setting the initial start value). It looks a bit odd in the code, so we could fix it by adding a function that creates the generator-iterator, does this init call, and returns it.


def elapsed_generator_factory():
    generator = elapsed_generator_fn()
    next(generator)
    return generator
	
elapsed = elapsed_generator_factory()
# do something
print(f"elapsed: {next(elapsed)}")

# do something
print(f"elapsed: {next(elapsed)}")

# do something
print(f"elapsed: {next(elapsed)}")

As I've said, it seems to me like a cool use for generators. If we want something more complete (that gives us the total time, that stores the different snapshots...) we should move on and end up with a simple class like this.


class Elapsed:
    def __init__(self):
        self.initial_start = None
        self.snapshots = {}

    def start(self):
        self.initial_start = time.time()
        self.start = self.initial_start

    def take_snapshot(self, name):
        now = time.time()
        self.snapshots[name] = now - self.start
        self.start = now
        return self.snapshots[name]
    
    def total(self):
        return time.time() - self.initial_start

    def retrieve_snapshots(self):
        return self.snapshots
		
    elapsed = Elapsed()
    elapsed.start()
    time.sleep(2)
    print(f"elapsed: {elapsed.take_snapshot('first')}")

    time.sleep(1)
    print(f"elapsed: {elapsed.take_snapshot('second')}")

    time.sleep(3)
    print(f"elapsed: {elapsed.take_snapshot('third')}")

    print(f"total elapsed: {elapsed.total()}")

    print(f"snapshots: {elapsed.retrieve_snapshots()}")


Friday, 3 June 2022

Python Type Hints and DI

After some initial reluctance I've started to use Python type hints for any non trivial code. I'm not strict at all (usually I don't declare all types, only when they are meaningful to me), and most times I don't enable the type checker (in vscode-pylance), I just want the sort of documentation that type declarations provide, and the improved intellisense experience. Somehow type hints in python seem much better to me than using typescript over javascript.

I've found something really interesting. We know that type hints are not enforced by the Python runtime (so Python remains as dynamic as always), they are intended to be used by third party tools before you run your code. This said, the interesting discovery to me is that the type information is available at runtime in form of annotations. So while the runtime won't impose any resctrictions based on these annotations, your code can use this information. In python 3.10 it's available through inspect.get_annotations(). I guess this is how the diffeent Dependency Injection libraries that have flourished in recentyears work.

This reminds me of how Dependency Injection works in Angular with TypeScript. So far, In JavaScript we don't have a standard way (like annotations) to add information (metadata) to our objects, but there is a proposal, the reflect-metadata api, and angular-polyfill.js takes care of adding it to our browser. If you add to your tsconfig.json file the emitDecoratorMetadata option (that also needs the experimentalDecorators option), TypeScript will save type information as metadata in the generated JavaScript (it generates code that adds this information to Reflect.metadata if the API exists). Example of generated JavaScript code:


var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);


__decorate([
    deco,
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String]),
    __metadata("design:returntype", void 0)


As explained here TypeScript will only do this for classes, functions... that have been decorated (with any decorator, you can just create a dummy one). You have a pretty nice explanation of how DI works in Angular-TypeScript here.