Understand Python Decorators

Standard Python skills are sometimes forgotten in today’s rush to learn pandas, matplotlib, numpy, scipy etc. Of course they are brilliant to learn and very rewarding, but it’s also nice to get back to basics!

Decorators are those funny @function written above the function you are calling. What do they mean?

At its simplest, a decorator is just a function that takes just one argument. That argument is the function being decorated.

Sounds complicated? It can be, but understanding what decorators do and how they work is not.

I’m going to use a simple example of a function which reverses the arguments given to it and simply prints them out to the screen.

func(1, 2 ,3) will print >> 3 2 1.

The function which reverses the arguments is cool but involves a bit of python trickery. We have to use the ‘*args’ method of passing arguments.

‘*args’ can pack arguments and can also unpack them. Let’s look at the example:

def foo(*args):
   a = args[::-1]
   print(f'original arguments {args}')
   print(f'reversed arguments {a}')

If we call foo(1,2,3), we get the following output

  • original arguments (1, 2, 3)
  • reversed arguments (3, 2, 1)

Although foo is called with (1,2,3), the foo function uses ‘*args’ which unpacks all the arguments. This means we can pass as many or as few as we like.

If we call foo(1,2,3,4,5), we get the following output

  • original arguments (1, 2, 3, 4, 5)
  • reversed arguments (5, 4, 3, 2, 1)

args[: : -1] is a simple line which is worth remembering. It uses list slicing to reverse a list!! Use [: : -1] whenever you want to reverse a list or string.

I’ll use that function to expand on decorators. It’s important to note that functions are first class objects in python. They can be treated in the same way as any other object and can be used as input to other functions.

def foo(func):
    def wrapper(*args, **kwargs):
        print(f'Calling function {func.__name__}')
        a = args[::-1]
        return func(*a)
    return wrapper
  • Line 1 defines our function, foo. It takes a function as it’s argument.
  • Line 2 defines another function called wrapper. This name is such by convention and you will see it often in decorators. It unpacks all the arguments given to func by using the *args convention. You can safely ignore **kwargs for now.
  • Line 3 simply prints “Calling function ‘func’
  • line 4 reverses our arguments
  • line 5 calls func with the packed reversed arguments *a and returns the output.
  • Line 6 returns the wrapper.

This is the basic form of a decorator function. The wrapper function does some work and calls the calling function.

This can be used as a decorator function by typing @foo above the function which will be called from your code.

@foo                
def reverse_args(*args):
    print(args)

The function reverse_args has now been decorated by the foo function! So how does it work?

  • reverse_args(1,2,3,4) will print 4 3 2 1.
  • reverse_args(‘day’, ‘the’, ‘is’, ‘This’) will print (‘This’ ‘is’ ‘the’ ‘day’)

This is about as simple as it gets to help understanding decorator functions. Just remember:

  • A decorator function is still just a plain old function.
  • The decorator function is what comes after the @ symbol.
  • The decorated function is what you finally use in your code.
  • Remember to use *args. It makes things easier.
  • The wrapper function is the function which does some work before calling the passed function. It’s called wrapper by convention to help understanding.

If you like it – share it!

Rotate a matrix in Python

The other day I had a coding interview and the following question flummoxed me.

You are given a list which represents a matrix as input to a function.

A = [ [1,2,3], [3,4,5], [6,7,8] ]

123
456
789
Matrix 1

Your job is to transform matrix 1 to matrix 2.

741
852
963
Matrix 2

Conditions

  • The method is in pure python – not numpy
  • The function should handle any size of matrix
  • The matrix is a square matrix

On the face of it this looks quite easy. The first thing to remember is that it is a list of lists where all internal lists are the same size. It requires slicing and dicing.

To test the output of the function you can use:

test = [[7,4,1], [8,5,2], [9,6,3]]

Lets define the function first.

def rotate_matrix(A)

I want to make a deep copy of the original matrix A, so I’m going to import ‘copy’. I also need to know the dimensions of the matrix based on the length of the list itself and the length of the row in the list which will be defined as ‘rows’ and ‘cols’. It will be helpful to have an empty list to store the rotated matrix in.

import copy
b = copy.deepcopy(A)
rows, cols = (len(A), len(A[0])
c = []

The trick is to gather all the ‘cells’ from the first column and make them the first row of the new matrix. Python lists start from Zero, so the first for loop will be for the columns:

for j in range(0, cols):

Next task is to gather the data from each column:

    for i in range(rows-1, -1, -1):
        c.append( a[i][j])
    b[j] = c
    c = []
return b

The first ‘for’ statement loops from 0 to 3. In python terms, it is actually 0 to 2 because it starts counting from zero and ends at 2. rather than 1 to 3.

The second ‘for’ loop starts from row – 1. That is 2 in this case. It counts down to 0 in steps of -1. The translation is [start, stop, step]. It is counting from 2 down to zero.

The temporary list is stored in the list variable ‘c’ and the first row of list ‘b’ is changed to the values in ‘c’.

‘c’ is then reset to empty for the next run and assignment.

So when ‘j’ = 0 then ‘i’ will = collect all the values from column 1 over all the rows of ‘a’ and store them in a temporary list, ‘c’. That is the assigned to the first row of ‘b’. So on and so forth through the double ‘for’ iterations.

At the end the list ‘b’ will hold the values for the transformed list, A. this returned to the function call.

B = rotate_matrix(A)

Test the result with rotate_matrix(A) == test. If True, you have succeeded!

You can test this out with lists of different sizes such as :

A = [ [ 1,2,3,4], [5,6,7,8], [9,10,11,12], [13,14,15,16] ]
test = [ [13,9,5,1], [14,10,6,2], [ 15,11,7,3], [16,12,8,4] ]

Interview tip

  • Read and understand the question
  • Ask questions from the interviewer to better understand
  • Think
  • What kind of data structure is being used – don’t jump to conclusions
  • What data structure answers the question
  • Learn more pure python!
A = [[1,2,3], [4,5,6], [7,8,9]]
test = [[7,4,1], [8,5,2], [9,6,3]]

#a = [[1,2,3,4], [5,6,7,8], [9,10,11,12], [13,14,15,16]]
#test = [[13,9,5,1], [14,10,6,2], [15,11,7,3], [16,12,8,4]]


def rotate_matrix(a):
    import copy
    rows, cols = (len(a), len(a[0]))
    c = []

    b = copy.deepcopy(a)    #Don't mess up the input data

    for j in range(0, cols):
        for i in range(rows-1, -1, -1):
            c.append(a[i][j])
        b[j] = c
        c = []

    return b

c = rotate_matrix(A)

if rotate_matrix(A) == c #True YES. False FECK.

Easy when you realise Column 0 reversed becomes Row Zero in the rotated matrix.

Comments and better code are always appreciated!!

Tweet if you like it!

The WHO says PCR tests are suspect!

Product type: Nucleic acid testing (NAT) technologies that use real-time polymerase chain reaction (RT-PCR) for detection of SARS-CoV-2 Date: 7 December 2020  

WHO-identifier: 2020/5, version 1 Purpose of this notice: To ensure users of certain nucleic acid testing (NAT) technologies are aware of certain aspects of the instructions for use (IFU) for all products. Description of the problem: WHO has received user feedback on an elevated risk for false SARS-CoV-2 results when testing specimens using RT-PCR reagents on open systems.  

As with any diagnostic procedure, the positive and negative predictive values for the product in a given testing population are important to note. As the positivity rate for SARS-CoV-2 decreases, the positive predictive value also decreases. This means that the probability that a person who has a positive result (SARS-CoV-2 detected) is truly infected with SARS-CoV-2 decreases as positivity rate decreases, irrespective of the assay specificity. Therefore, healthcare providers are encouraged to take into consideration testing results along with clinical signs and symptoms, confirmed status of any contacts, etc.

Source: WHO Information Notice for IVD Users

Well WHO would have thunk it?

The WHO have finally advised on, not only the danger of false positives based on CT cycles but also on the PPV based on prevalence of the infection of SARS-CoV2.

In fact the advice PPV was the first paragraph of their notice. Whilst this is well known amongst health professional, no guidance to those testing ‘positive’ has ever been given by any government.

I have covered this in a previous article The Mathematics of Covid-19 Testing.

It’s a simple matter of Bayesian Probability. Obviously government ministers can’t do mathematics.

Will governments revise their numbers of Covid positive? Aye right!

The price of covid madness. Virus drives up redundancies to record high | Daily Mail Online

A total of 370,000 workers lost their jobs in the three months to October, according to the Office for National Statistics – 217,000 more than in the previous three months.

Source: Virus drives up redundancies to record high | Daily Mail Online

The ‘virus’ has not driven up unemployment. Government policies have.

The big takeaway from this article is the £43 BILLION spent on government subsidised wages (furlough).

£43 Billion.

Let that sink in for a minute. It’s a difficult number to make sense of, so here is some things to put it into context.

  • £43 billion is roughly 29% of the UK NHS annual funding.
  • With £43 billion you could buy 215,000 houses at £200k each!
  • 43 billion miles is 89,996 round trips to the moon.
  • There are 7.8 billion people on the planet. With £43 billion you could afford to give each one £5.51
  • Bill Gates has over £50 billion. With £43 billion you could tell him to fuck right off.

This is “just” the cost of furlough. When the rests of the costs to society such as loss of GDP, donations to pharmaceutical companies, building empty Nightingale hospitals, loss of tax revenues, unemployment benefits, quantitative easing….the true cost will be measured in trillions.

This is madness. It is insane. It will have repercussions for years to come. Many more people will suffer ill health and die because the NHS is now the National Coronavirus Service. Got an appointment to treat your cancer? Hard cheese. It’s cancelled.

Todays children will suffer for decades. No education. No job. No future.

All to save Granny and give her a couple of more years of life. Selfish bitch!

Cui Bono? It ain’t you.

Austria: Live PCR test in Parliament: Coca Cola tests COVID-19 positive – Europe – Israel National News

Austrian MP administers COVID-19 PCR test to beverage Coca Cola in plenum before colleagues. Popular drink tests positive for COVID-19.

Source: Austria: Live PCR test in Parliament: Coca Cola tests COVID-19 positive – Europe – Israel National News

A wonderful Christmas toy for the children. See how many mad things you can test that are Covid positive. I’d love to see a nip of Glen Morangie test positive.

The money that has been spent on this nonsense is absolutely staggering.

The people who were turfed out of hospital into care homes and left to rot is nothing less than government sponsored euthanasia.

The ‘heroes’ of the NHS filmed themselves on Tik Tok dancing round handbags and were applauded for doing fuck all.

Meanwhile, back on the ranch, small businesses, large businesses, pubs, high streets, cafes…….you name it have all suffered and will probably never recover.

Pharmaceutical companies, whose business models were failing are now laughing all the way to the Bank. Billions to investigate “the virus”. Billions to develop “the vaccine”. Billions of tax-payer money used to buy “vaccines” (they are not vaccines in the accepted understanding of the word) to “battle, combat, fight” (substitute whichever military term you like) for a virus with a 99.8% recovery rate which kills virtually no-one.

And don’t forget the sight of human beings walking and incredibly, driving, around in the open air with a piece of cloth wrapped round their faces.

These truly are disturbing times.

October suicide deaths surpass total coronavirus deaths in Japan – The Jerusalem Post

Male suicides have increased 22% in October compared to October 2019, but rates of suicides among women have increased 83% over the same time frame.

Source: October suicide deaths surpass total coronavirus deaths in Japan – The Jerusalem Post

Scots to get covid vaccine ‘next month’ as health secretary sets out ambitious plan – Daily Record

Jeane Freeman announced who is first in line and how long it could take to cover the country.

Source: Scots to get covid vaccine ‘next month’ as health secretary sets out ambitious plan – Daily Record

Scotland officially became a Police State at 18:00 hours, Friday the 19th of November.

The previous day the collection of inept muppets formally known as the Scottish Government announced that 4.4 million people in Scotland would be vaccinated by March next year.

The ‘Health’ Minister, Jeane Freeman (pictured above asking for help in finding a clue) had this unadulterated nonsense to say:

“For now, the important thing is that when we start to deliver these first vaccines, it will be on the basis that they offer some form of protection, even if we don’t at this stage, know exactly how much protection that is. And it will be safe. So when we get in touch with you, please go for the vaccine. It offers you a level of protection we don’t have through any other means.”

She does not know if the vaccine will have any effect or which vaccine it will be, but it ‘will be safe’ because there is fuck all else they can think of doing.

Baldric himself would have been highly impressed with Freeman’s fuckwitted cunning plan. Let’s inject an untried and untested substance with unknown effectiveness into a population 95% of whom will never in the slightest way be affected by the ‘deadly virus’.

Neither Pfizer nor Moderna has yet to receive a license to push their rapidly produced snake oils on the population. When and if they do, neither company will be liable for any injuries the potion may cause in the population.

Will Freeman be exempt from prosecution? Her department is the provider of these drugs and she is the head dealer.

Covid-19: politicisation, “corruption,” and suppression of science | The BMJ

Fighting talk from Kamran Abbasi, executive editor of the BMJ. About time too!!!

When good science is suppressed by the medical-political complex, people die. Politicians and governments are suppressing science. They do so in the public interest, they say, to accelerate availability of diagnostics and treatments. They do so to support innovation, to bring products to market at unprecedented speed. Both of these reasons are partly plausible; the greatest deceptions are founded in a grain of truth. But the underlying behaviour is troubling.Science is being suppressed for political and financial gain. Covid-19 has unleashed state corruption on a grand scale, and it is harmful to public health.

1 Politicians and industry are responsible for this opportunistic embezzlement. So too are scientists and health experts. The pandemic has revealed how the medical-political complex can be manipulated in an emergency—a time when it is even more important to safeguard science.The UK’s pandemic response provides at least four examples of suppression of science or scientists. First, the membership, research, and deliberations of the Scientific Advisory Group for Emergencies (SAGE) were initially secret until a press leak forced transparency.

2 The leak revealed inappropriate involvement of government advisers in SAGE, while exposing under-representation from public health, clinical care, women, and ethnic minorities. Indeed, the government was also recently ordered to release a 2016 report on deficiencies in pandemic preparedness, Operation Cygnus, following a verdict from the Information Commissioner’s Office.34 …

Click the link below for the complete article.

Source: Covid-19: politicisation, “corruption,” and suppression of science | The BMJ

The Covid Physician’s true coronavirus timeline | The Covid Physician | The Critic Magazine

Valentine’s Friday, 2020. A quarter century practising medicine. Half in hospitals, half in general practice. I’d been treating unseasonal, politely-coughing, relatively-well patients for the previous…

Source: The Covid Physician’s true coronavirus timeline | The Covid Physician | The Critic Magazine

A must read from a medical professional which covers the complete stupidity of the SARS-CoV 2 nonsense. The most monumental con in the history of……..monumental cons.

Once lost, freedom is hard to regain – spiked

“We must not sacrifice civil liberties at the altar of security.”

Source: Once lost, freedom is hard to regain – spiked

Liberty is your children’s future. It is not the whim of any campaign shouting , corrupt politician or his financially compromised ‘Scientists’.

What is taken away will never be given back.

Step into freedom and throw the mask away.

Design a site like this with WordPress.com
Get started