Advanced Python Interview questions list, should know every python programmers.

AJ Auntor
4 min readOct 26, 2021

--

AJ Auntor python Interview
Python Interview

Many of these are confusing and intended for mid-level developers who need a solid understanding of Python as a language as well as how it works on the inside.

01. Where do nolocal and global keywords come from?

Changing the scope of a previously declared variable is done with these two keywords. When nested functions are used, nolocal can be used to access a variable:

def func1():
x = 5
def func2():
nolocal x
print(x)
func2()

Global instructions are more straightforward. They make previously declared variables global. Consider the following code:

x = 5
def func1():
print(x)
func1()
> 5

Since x is declared before function call, func1 can access it. However, if you try to change it:

x = 5
def func2():
x += 3
func2()
> UnboundLocalError: local variable 'c' referenced before assignment

To make it work, we need to indicate that by x we mean the global variable x:

x = 5
def func2():
global x
x += 3
func2()

02. Classmethod vs. staticmethod: what’s the difference?

Their class methods are both callable without instantiating an object of the class. However, their signatures are different:

class A:
@staticmethod
def func1():
pass

@classmethod
def func2(cls):
pass

You can see that classmethod can be passed an implicit argument cls, which is automatically set to the class A itself. Creating alternative inheritable constructors is one of the most common uses for classmethod.

03. How does GIL work and how can it be avoided?

GIL stands for the Global Interpreter Lock, a concurrency mechanism implemented by Python. It is deeply engrained into the Python code and can’t be removed at the moment. GIL introduces a significant downside in that it does not permit threads to be truly concurrent. The interpreter is locked, and even though you appear to be working with threads, there are no threads executing at the same time, degrading performance.

04. When are metaclasses used and what are they used for?

A metaclass is a class for another class. It is possible to specify certain behaviors that are common to many classes using a metaclass in situations where inheritance is too messy. Abstract classes are often created by using ABCMeta, a metaclass.

05. Type annotations are what they sound like, Why do generic type annotations exist?

The Python language is dynamically typed, but there is a way for types to be annotated to reduce confusion. Below is a list of built-in types:

  • int
  • float
  • bool
  • str
  • bytes

In the typing module, complex types are available:

  • List
  • Set
  • Dict
  • Tuple
  • Optional
  • etc.

An example of how a type annotation would be used on a function is as follows:

def func1(x: int, y: str) -> bool:
return False

There are generic type annotations, which allow you to specify complex logic by taking another type as a parameter:

  • List[int]
  • Optional[List[int]]
  • Tuple[bool]

You only need to use these to check for static types and for warnings. Runtime will not guarantee their existence.

06. How do generator functions work?

The generator function allows its execution to be suspended after returning a value, so that it can be resumed at a later time and return yet another value. Yield, which replaces return, allows you to do this. If you’ve worked with generator functions, you might have worked with range. I will leave it as an exercise to come up with a way to implement it (the example only works with positive steps, I’ll leave it to you to make one that supports negative steps):

def range(start, end, step):
cur = start
while cur > end:
yield cur
cur += step

07. How do decorators work in Python?

A Python decorator modifies the behavior of a function. In the case of logging all calls to a specific set of functions, caching their parameters and return values, and performing benchmarks, for instance.

08. How does Python pickle and unpickle?

Pickling is just another way to say serializing in Python. Using Pickling, you can serialize an object into a string (or any other string you choose) for persistence on storage or network transmission. An unpickled string can be restored to its original state by restoring the pickled object.

Pickle is not secure. Only unpickle objects from trusted sources

This is how a basic data structure would be pickled:

import picklecars = {"Subaru": "best car", "Toyota": "no i am the best car"}
cars_serialized = pickle.dumps(cars)
# cars_serialized is a byte string
new_cars = pickle.loads(cars_serialized)

09. How do Python functions use *args and **kwargs?

Unpacking is closely linked to these. All unnamed arguments will be stored in the args array if *args is included in the function’s parameter list. If **kwargs is used instead, all named arguments will be stored in the args array:

def func1(*args, **kwargs):
print(args)
print(kwargs)

func1(1, 'abc', lol='lmao')
> [1, 'abc']
> {"lol": "lmao"}

10. How can .pyc files be used?

Python bytecode is contained in .pyc files, just as Java class files are. The compilation phase of Python occurs when you run the program, unlike Java, where they are clearly separated. However, Python is still considered an interpreted language.

11. How do will you define abstract classes in Python program?

The ABC class is inherited from the abc module to define the abstract class:

from abc import ABC

class AbstractCar(ABC):
@abstractmethod
def drive(self):
pass

To implement the class, just inherit it:

class ToyotaSupra(AbstractCar):
def drive(self):
print('brrrr sutututu')

Regards and best wishes for your next interview. If I should include any questions, please let me know in the comments. Thank you for reading.

Closing remarks………Never give Up…keep learning.

--

--