Skip to content

Simplifying version definitions #91

@illusional

Description

@illusional

Python can dynamically generate classes 😱

We could do some clever stuff to automatically generate these classes, for example:

from abc import ABC, abstractmethod

class BaseClass(ABC):
    def __init__(self, a=1):
        self.a = 1

    @abstractmethod
    def to_override(self):
        pass


class WithInheritedMethod:
    def to_override(self):
        print("Created a class called: " + self.__class__.__name__)


name = "CreatedClass"
globals()[name] = type(name, (WithInheritedMethod, BaseClass), {})

CreatedClass().to_override() # prints "Created a class called: CreatedClass"

We could apply a similar tactic to ToolVersions, for example to create a fully functional tool definition for Gatk4ApplyBqsr for each version of GATK, we could use:

versions = [Gatk_4_0_12, Gatk_4_1_2_0, Gatk_4_1_3_0, Gatk_4_1_4_0]


names = []
for v in versions: 
    # prepare the class name (NB: this is different to what we've used in the past)
    name = f"{Gatk4ApplyBqsrBase.tool(None)}_{v.__name__[5:]}"
    globals()[name] = type(name, (v, Gatk4ApplyBqsrBase, object), {})
    names.append(name)

# This overrides the exports and makes sure ONLY the created classes are exported
__all__ = names

Caveats

It does bring intellisense, pycharm / vscode can't determine that the import actually exists (red squiggly line):

image

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions