sandeepk

Git rebase is a very handy command to integrate changes from one branch to another, we can run git rebase in two modes manual and interactive. In manual all commit take from the current branch and applied over the head of the passed branch, but in case of the interactive rebase command you have more control over the option to what do with commits.

So to understand how rebase work, we take an example where we have a master branch with the following commits.

>>> git log
commit 8bfb8c19c3d7b795e9698a9818880d89ca3c214a
Author: Sandeep <sandeepchoudhary1507@gmail.com>
Date:   Sun Jun 14 01:06:07 2020 +0530

    New goals added

from this master branch, we create a new branch dev and do some changes/bug fixes.

>>> git checkout -b dev master
...
>>> git log
commit a05b6cd75e604df0f4434a574809a4fc14e4313e
Author: Sandeep <sandeepchoudhary1507@gmail.com>
Date:   Sun Jun 14 01:08:11 2020 +0530

    workaround bugs

commit 8bfb8c19c3d7b795e9698a9818880d89ca3c214a
Author: Sandeep <sandeepchoudhary1507@gmail.com>
Date:   Sun Jun 14 01:06:07 2020 +0530

    New goals added

but in between the other developer push changes in the master branch and to integrate that changes in your current branch you can use merge or rebase command, the rebase helps you maintain the liner history of your workflow.

>>> git checkout master
>>> git log
commit 3c5d6baf13aeac37d9efb1218bbf3240ec5c2a12
Author: Sandeep <sandeepchoudhary1507@gmail.com>
Date:   Sun Jun 14 01:07:29 2020 +0530

    new release added

commit 8bfb8c19c3d7b795e9698a9818880d89ca3c214a
Author: Sandeep <sandeepchoudhary1507@gmail.com>
Date:   Sun Jun 14 01:06:07 2020 +0530

    New goals added

so now to integrate new changes from master to your branch dev, without making the commit history complex, we can use rebase command, let's check out

>>> git checkout dev
>>> git rebase master
>>> git log
commit 184805896dd5684fc076b9bb9aa34eb3994251b1
Author: Sandeep <sandeepchoudhary1507@gmail.com>
Date:   Sun Jun 14 01:08:11 2020 +0530

    workaround bugs

commit 3c5d6baf13aeac37d9efb1218bbf3240ec5c2a12
Author: Sandeep <sandeepchoudhary1507@gmail.com>
Date:   Sun Jun 14 01:07:29 2020 +0530

    new release added

commit 8bfb8c19c3d7b795e9698a9818880d89ca3c214a
Author: Sandeep <sandeepchoudhary1507@gmail.com>
Date:   Sun Jun 14 01:06:07 2020 +0530

    New goals added

we can also run the rebase command in —interactive mode which gives us the option to edit/squash/... the commits

>>> git rebase -i master
pick 1848058 work around bugs

# Rebase 3c5d6ba..1848058 onto 3c5d6ba (1 command(s))
#
# Commands:
# p, pick = use commit
# r, reword = use commit, but edit the commit message
# e, edit = use commit, but stop for amending
# s, squash = use commit, but meld into previous commit
# f, fixup = like "squash", but discard this commit's log message
# x, exec = run command (the rest of the line) using shell
# d, drop = remove commit
#
# These lines can be re-ordered; they are executed from top to bottom.
#
# If you remove a line here THAT COMMIT WILL BE LOST.
#
# However, if you remove everything, the rebase will be aborted.
#
# Note that empty commits are commented out

One of the cool use of the git rebase command is that you can change the base of the branch from one branch to other by use of —onto option.

Let assume you create a branch featureA from master and then another branch featureB from featureA, to change the base of the featureB branch.

# git rebase --onto <newbase> <oldbase>
>>> git rebase --onto master featureA featureB

So this is all about the git rebase command, which can help you to keep your commit history clean and your current working branch commits sync with the master branch.

#git

In this post, we will talk about the standard python library decorators and one or more things about the decorators . If you haven't read the previous blog post about decorator, go check out that here. I will be waiting...

We will talk about functools.lru_cache Decorator from Python standard Library, where lru means Least Recently Used.

lru_cache as the name suggested, it saves the previous result of the function expression based on argument and uses that result if the same argument passed. To save expensive calculations.

functools.lru_cache(maxsize=128, typed=False)

maxsize means that numbers of cache result which can be cached, once the cache is full the older result is discarded. One should use maxsize value as a power of 2 for optimal performance.

type true means argument will be treated differently as int and float values as 1 and 1.0 are treated the same, but if type value is set to true it will be treated differently.

>> 1 == 1.0
>> True

lru_cache use dict to the save the argument as position and keyword-based so all the argument passed to the decorator should be hash-able.

Some point as notes to remember about the decorators

  • Decorators are executed when the module is loaded by Python and decorated function only executed if explicitly invoked.
  • Decorators have the power to return the entirely a different function.
  • We can also have a parameterized decorator as we have seen in the lru_cache decorator.
  • Stocked Decorators means when more then one decorator is applied to a function, then the order of execution, is from the decorator nearest to the function definition to outside. Let seen an example
@d2
@d1
def func:
    print('f')

func = d2(d1(func))

so that wrap from my side on the topic Decorators.

#python

Decorators attach additional responsibility to the object dynamically. A decorator takes other function as an argument which it processes and returns that function or any other callable object.

So how the decorator looks like

@clean_strings
def get_full_name(first_name, middle_name, last_name):
    return first_name + middle_name + last_name

In above code snippet we have a decorator clean_strings, this can also be written in this way.

def get_full_name(first_name, middle_name, last_name):
    return first_name + middle_name + last_name

get_full_name = clean_strings(get_full_name)

There are one two things we will talk about decorator after understanding.

  • Variable Scope
  • Closure

Variable Scope

In every language, the variable has a scope where they are accessible and where not. So here we will talk about the local scope and global scope lets jump right into the code to see

def show(a):
    print(a)
    print(b)
>>> show(10) 
10
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in show
NameError: name 'b' is not defined 

We got the error as b is not defined in the scope

b = 101
def show(a):
    print(a)
    print(b)
>>> show(10) 
10
101

here its work fine as b is defined in the global scope, which can be accessed from within the function. let see another code snippet.

b = 101
def show(a):
    print(a)
    print(b)
    b =190
>>> show(10) 
10
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in show
UnboundLocalError: local variable 'b' referenced before assignment

here we face error as code interpret b as local variable of the function which being accessed before declaring as it is defined in the scope of the function. To treat b as global variable despite the assignment in function we can use global declaration.

b = 101
def show(a):
    global b
    print(a)
    print(b)
    global b =190
>>> show(10) 
10
101
>>> b
190

Closure

Closure are the function which have access to the non global variables referenced in the body of function.

Closure image

Figure from Fluent Python Book, chapter 7

In Python3 nonlocal was introduced which allows assigning the variable inside the scope.

Consider an avg function to compute the mean of an ever-increasing series of values; for example, the average closing price of a commodity over its entire history. Every day a new price is added, and the average is computed taking into account all prices so far.

def avg_series():
    count = 0
    total = 0
    def averager():
        nonlocal count, total
        count += 1
        total += new_value
        return total / count

    return averager

The need of using nonlocal here is that if we don't, Python assumes that count and total are the local variable of averager method, which will break our logic.

Code example is taken from Fluent Python Book.

Now lets build a decorator that can logs the runtime for the function.

import time
def log_time(func):
    def clocked(*args):
        start_time = time.time()
        result = func(*args)
        elapsed_time = time.time() - start_time
        print("Elapsed time: {}".format(elapsed_time))
        return result
    return clocked    

There are also built-in decorators in Python Standard Library which we will discuss in the next blog post, so stay tuned till then cheers.

#python

Function are the code block which contain a logic to process on certain set of given input and return an output. Functions in Python are the First Class Object which basically means function as entity can be

  • Create at Run-time.
  • Passed as argument to function.
  • Return as result from the function.
  • Assigned to the variables.

Some functions are also called as Higher Order Function which means that a function which take other function as an argument or return a function as result. Example of higher order function in Python are Map, Filter, Sorted ...

Let see in Python function are classes or not and try to prove above all points to show in Python Function are First Class Object.

Creating function at run-time in console.

def add(x, y):
    return x+y

add(2, 4)
6
type(add)
<class 'function'>

Assigned to the variable

sum = add
sum
<function add at 0x7f2199555b70>
// notice above sum variable pointing to the add function.
sum(3, 4)
7

Passing function as argument.

list(map(add, range(5), range(5))) // here we pass *add* function as argument to the *map* function.
[0, 2, 4, 6, 8]

Returning function as result.

def factorial(x):
    if x < 1:
        return 1
    else:
        return x * factorial(x-1) // here we are returning a function

Above code snippets clearly show that function in Python are First Class Object.

#python