How to create dict functions in Python?

I am writing a database migration script in Python in which I am creating a dictionary that can transfer a database between versions. I am currently doing this as follows:

def from1To2():
    pass  # migration script here
def from2To1():
    pass  # migration script here
# etc

migrations = {
    1: {'up': from1To2},
    2: {'down': from2To1, 'up': from2To3},
    3: {'down': from3To2, 'up': from3To4},
    4: {'down': from4To3},
}

But every time I create a new migration, I need to write two migration scenarios (up and down) and put them in the migration dictionary. Since the migration functions are really small (usually two lines), I thought about writing them directly in the migration migration dict. In Javascript, it looks something like this:

migrations = {
    1: {
        'up': function(){ addSomeColumn(); recordChange(); }, 
        'down': function(){ dropSomeColumn(); recordChange(); }
    },
    2: etc
}

Since migration functions are often two lines, I don't think I can use lambda functions. Does anyone know of any other way to directly write functions in a dict in Python? All tips are welcome!

+4
3

:

migrations = {}

def migrate(old_version, new_version):
    assert abs(new_version-old_version)==1

    def decorator(f):
        direction = 'up' if new_version > old_version else 'down'
        if old_version not in migrations:
            migrations[old_version] = {}
        migrations[old_version][direction] = f
        return f
    return decorator

@migrate(1, 2)
def upgrade():
    pass  # migration script here

@migrate(2, 1)
def downgrade():
    pass  # migration script here

@migrate(2, 3)
def upgrade():
    pass  # migration script here
# etc

print(migrations)

:

{1: {'up': <function upgrade at 0x02BE4588>}, 2: {'down': <function downgrade at 0x02BE4618>, 'up': <function upgrade at 0x02BE4540>}}

migrations, (, 1 2 - 2 3 ).

+6

:

>>> function_dictionary = {'capitalize': lambda text: text.capitalize()}
>>> function_dictionary['capitalize']('word')
'Word'
0

You can use lambda: addSomeColumn() and recordChange()to return your functions True.

0
source

Source: https://habr.com/ru/post/1606938/


All Articles