1 year ago

#344332

test-img

Miguel Guthridge

How can I implement static function version checking for module stubs in Python?

So I've created some stub code for a proprietary API so that I can write code with autocompletions and inline documentation.

"""my_mod

Stub code for the my_mod module
"""

def do_thing(a: int, b: int):
    """Performs some complex operation
    Included since API version 1.3
    """

def do_other_thing(a: str, b: float):
    """Performs some other complex operation
    Included since API version 1.4
    """

Since this API has many minor updates (we're up to 1.20), it can be difficult to manage what functions are available in what versions, especially since I want to target slightly older versions to ensure people can use my software without needing to run the latest versions of the host software to get the latest API version.

This leads me to my problem: how can I, after specifying a version I wish to target, use some kind of static analysis to ensure that my code doesn't call code that won't be available in that version of the API, unless I use some kind of version narrowing statement. It needs to be done through static analysis since it would be extremely difficult to create a testing environment where I could get full code coverage since I'd effectively need to emulate the entire environment my program runs in.

I'm looking for something like the following:

import version_checker
version_checker.targeting((1, 3))

import my_mod

my_mod.do_thing(1, 2) # Ok, we're targeting that version

my_mod.do_other_thing("Hi", 1.0) # Not ok, that will break for people using API v1.3

if version_checker.check(1, 4): # If the running API version is >= 1.4
    my_mod.do_other_thing("Hi", 1.0) # Ok, since we've got a version check built-in

I'm happy to modify the stub code by using decorators or something to specify versions and stuff. Something like a decorator would be really good for this.

@version(1, 3)
def do_thing(a: int, b: int):
    """Performs some complex operation
    Included since API version 1.3
    """

The solution would preferably also support specifying modifications to the function definitions over different versions (eg in v1.5, do_thing() could have an additional optional parameter c).

Although this would hardly be a common problem, I don't think it's rare enough that there wouldn't be any solutions available.

python

versioning

static-analysis

python-typing

0 Answers

Your Answer

Accepted video resources