0% found this document useful (0 votes)
160 views

Codingcompiler Com Python Coding Interview Questions Answers

The document discusses 141 Python coding interview questions and answers to help prepare for Python coding interviews. It includes questions for both freshers and experienced Python developers, covering topics like basic Python syntax, debugging, NumPy arrays, strings, and more. The questions are organized into sections and include the question, expected output, and an explanation.

Uploaded by

Sarathi M
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
160 views

Codingcompiler Com Python Coding Interview Questions Answers

The document discusses 141 Python coding interview questions and answers to help prepare for Python coding interviews. It includes questions for both freshers and experienced Python developers, covering topics like basic Python syntax, debugging, NumPy arrays, strings, and more. The questions are organized into sections and include the question, expected output, and an explanation.

Uploaded by

Sarathi M
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

Programming Java Python Machine Learning Blockchain Interview Questions Reviews

Stories

Python Coding Interview Questions Search

And Answers
by Coding Compiler

Preparing for Python coding interviews? If your answer is yes, then you are right
place. 141 Python Coding Interview Questions and Answers will help you crack
your following Python code interview.

Here Codingcompiler shares a very good list of 141 Python coding interview
questions for freshers and experienced. These Python coding questions are prepared
by expert Python developers. If you are a fresher or experienced in Python coding,
definitely, these interview questions on Python will help you to refresh your
coding knowledge to cross the line in your next Python job interview. All the best for
your future and happy python coding.

Table of Contents

Python Coding Interview Questions For


Freshers
1. Write a Python Code to Check if a Number is Odd or Even.
2. Write a Python code to find the maximum of two numbers.
3. Write a Python code to check prime numbers.
4. Write a Python factorial program without using if-else, for, and ternary
operators.
5. Write a Python code to calculate the square root of a given number.
Recent Posts
6. Write a Python code to calculate the area of a triangle.
7. Write a Python code to check the armstrong number.
8. Write a Python code to check prime numbers. Python Pandas – A powerful
9. Write a Python code to display a multiplication table using for loop. library for data manipulation
10. Write a Python code to swap two variables. and analysis
What Tools Do Data Scientists
Use?

Python Coding Interview Questions For Firebase Vs Heroku – A Detailed


Guide on the Difference
Experienced Between Firebase and Heroku
Top 10 Best Programming
1. How do you debug a Python program?
Languages ​for Game
2. What is <Yield> Keyword in Python?
Development
3. How to convert a list into a string?
4. How to convert a list into a tuple? Oracle and SAP ERP software
5. How to convert a list into a set? suites – which one is better for
6. How to count the occurrences of a particular element in the list? your career?
7. What is NumPy array? Which Programming Language
8. How can you create Empty NumPy Array In Python? is Better for Beginners?
9. What is a negative index in Python?
15 Best Companies for Software
10. How do you Concatenate Strings in Python?
Engineers in India
What is IBM DataPower? What is
DataPower used for?
Python Basic Coding Interview Questions Considering a Career in Coding?
How Long Does It Take to Learn
1) Write the output for the below Hello, Python Coding Skills?
commands. CRM Software – Its Types,
Features & Benefits
print('Hello, Python!')
print("Hello, Python!")
print('''Hello, Python!''')
print('"Hello, Python"')
print("'Hello, Python'")

Output

Hello, Python!
Hello, Python!
Hello, Python!
“Hello, Python!”
‘Hello, Python!’
Categories
Explanation: In Python programming, a string can be enclosed inside single quotes,
double quotes, or triple quotes.
Select Category

2) What is the output of the Python add two


numbers program?
Python Add Two Numbers Program

#Python Add Two Numbers Program


number1 = 5
number2 = 4
Top Categories
# Add two numbers
sum = number1 + number2
# Display the sum of the two numbers
print('The sum of the two numbers is:' sum)
Interview Questions
Output of the program: Programming
C Programming
File “”, line 7 Java Programming
print(‘The sum of the two numbers is:’ sum) Python Programming
^
RPA
SyntaxError: invalid syntax

The above Python add two numbers program throws SyntaxError because, the
comma(,) is missing in print statement. The below print statement will give you the
sum of the two numbers.

print('The sum of the two numbers is:', sum)

3) What is the output of the below sum of the two


numbers Python program?
num1 = input('Enter first number: ')
num2 = input('Enter second number: ')
sum = num1 + num2
print('The sum of the numbers is', sum)

The output of the sum of the two numbers program

Enter first number: 15


Enter second number: 10
The sum of the numbers is 1510

Python input() function always converts the user input into a string. Whether you
enter an int or float value it will consider it as a string. We need to convert it into
number using int() or float() functions. See the below example.

Read the input numbers from users Technology

num1 = input(‘Enter the first number: ‘)


num2 = input(‘Enter the second number: ‘)

15 Best Companies for Software


Converting and adding two numbers using int() & float() functions
Engineers in India

sum = int(num1) + int(num2) What is IBM DataPower? What is


sum2 = float(num1) + float(num2) DataPower used for?
Making an MMO: Coding, Cash,
Displaying the sum of two numbers and Crises
Top 5 Things You Must Know
print(‘The sum of {0} and {1} is {2}’.format(num1, num2, sum))
Before Entering Into The Crypto
print(‘The sum of {0} and {1} is {2}’.format(num1, num2, sum2))
Industry

The output of the sum of the two numbers program Can You Pay Bills with Bitcoin?
Top 10 Benefits of Paying with
Enter the first number: 15 Cryptocurrencies
Enter the second number: 10
Top 10 Benefits of Blockchain
The sum of 15 and 10 is 25
Technology for Business
The sum of 15 and 10 is 25.0
Launch story behind Shardeum-
Blockchain by WazirX
4) Write a Python program to illustrate arithmetic Why did this Budget Day see
operations (+,-,*,/)? 30%-50% Signups to Crypto
Exchanges?
Here is the Python arithmetic operators program:
Top 10 Best Laptops For
AutoCAD In India
# Read the input numbers from users
num1 = input('Enter the first number: ')
num2 = input('Enter the second number: ')

# Converting and adding two numbers using int() & float() functions
sum = int(num1) + int(num2)

# Subtracting the two numbers


sub = int(num1) - int(num2)

# Multiplying two numbers


mul = float(num1) * float(num2)

#Dividing two numbers


div = float(num1) / float(num2)

# Displaying the results of arithmetic operations


print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))
print('The subtration of {0} and {1} is {2}'.format(num1, num2, sub))
print('The multiplication of {0} and {1} is {2}'.format(num1, num2, mul))
print('The division of {0} and {1} is {2}'.format(num1, num2, div))

The output of the Python arithmetic operators program

Enter the first number: 25


Enter the second number: 10
The sum of 25 and 10 is 35
The subtraction of 25 and 10 is 15
The multiplication of 25 and 10 is 250.0
The division of 25 and 10 is 2.5

5) Python Program to Check if a Number is Odd or


Even.
#Python program to check if a number is odd or even

#To get the input from user


num1 = input("Enter a number: ")

#Checking whether the entered number is odd or even


if (int(num1) % 2) == 0:
print("{0} is Even number".format(num1))
else:
print("{0} is Odd number".format(num1))

The output of the Python odd or even program

Enter a number: 4
4 is Even number

Enter a number: 5
5 is Odd number

6) Write a Python program to find the maximum of


two numbers?
Here is the Python program to find the maximum of two numbers:

#To read the input value from the user


num1 = input('Enter the first number: ')
num2 = input('Enter the second number: ')

#Finding the maximum value using Python max() funtion


maximum = max(int(num1), int(num2))

#Displaying the maximum number


print("The maximum number is: ",maximum)

The output of the Python program to find the maximum number

Enter the first number: 23


Enter the second number: 45
The maximum number is: 45

7) Write a Python program to check prime


numbers.
Here is the Python program to check whether a number is prime or not:

# Function to check prime number


def PrimeChecking(num):
# Condition to check given number is more than 1
if num > 1:
# For look to iterate over the given number
for i in range(2, int(num/2) + 1):
# Condition to check if the given number is divisible
if (num % i) == 0:
#If divisible by any number it's not a prime number
print("The number ",num, "is not a prime number")
break
# Else print it as a prime number
else:
print("The number ",num, "is a prime number")
# If the given number is 1
else:
print("The number ",num, "is not a prime number")
# Input function to take the number from user
num = int(input("Enter a number to check prime or not: "))
# To print the result, whether a given number is prime or not
PrimeChecking(num)

#Output1 of the above Python program to check the prime number

Enter a number to check prime or not: 10


The number 10 is not a prime number

#Output2 of the above Python program to check the prime number

Enter a number to check prime or not: 37


The number 37 is a prime number

8) Write a Python factorial program without using


if-else, for, and ternary operators.
Yes, we can write a Python program to find the factorial of a number using in-built
Python functions.

math.factorial() function returns the factorial of a given number. Let’s have a look at
the Python factorial program using a math function:

# Python program to find factorial of a given number

#importing the math function


import math

#Defining the factorial() function to find factorial


def factorial(num):
return(math.factorial(num))

# Input function to get the number from user


num = int(input('Please enter a number to find the factorial: '))

#Printing the factorial of the given number


print("The factorial of the given number", num, "is",
factorial(num))
Output1 of the Python factorial program

Please enter a number to find the factorial: 5


The factorial of the given number 5 is 120

The output2 of the Python factorial program

Pleas enter a number to find the factorial: 10


The factorial of the given number 10 is 3628800

9) Write a Python program to calculate the square


root of a given number.
Here is the Python Program to calculate the square root:

# Input function to get the input from the user


n = float(input('Enter a number: '))

#Formula to calculate the square root of the number


n_sqrt = n ** 0.5

#Printing the calculated square root of the given number


print('The square root of {0} is {1}'.format(n ,n_sqrt))

Output1 of the Python program to find the square root

Enter a number: 2
The square root of 2.0 is 1.4142135623730951

Output2 of the Python program to find the square root

Enter a number: 4
The square root of 4.0 is 2.0

10) Write a Python program to calculate the area


of a triangle.
To calculate the area of a triangle we need the values of side one, side two, side three,
and the semi-perimeter. Let’s have a look at the Python area of the triangle program:

# Python Program to find the area of a triangle

# Get the 3 sides of a triangle from the user


s1 = float(input('Enter first side value: '))
s2 = float(input('Enter second side value:'))
s3 = float(input('Enter third-side value:'))

#Calculating the semi-perimeter of a triangle


sp = (s1 + s2 + s3) / 2

#Calculating the area of a triangle


area = (sp*(sp-s1)*(sp-2)*(sp-s3)) ** 0.5

#Printing the area of the triangle


print('The area of the triangle is: ', area)

The output of the Python area of the triangle program

Enter first side value: 3


Enter the second side value:4
Enter third-side value:5
The area of the triangle is: 8.48528137423857

11) Write a Python program to check Armstrong’s


number.
The armstrong number can be defined as n-digit numbers equal to the sum of the nth
powers of their digits are called armstrong numbers.

Armstrong Number Example:

153 is a armstrong number.

n=3 (numbr of digits)

nth powers of the digits – (111), (555), (333)

The number should equal the nth power of their digits, i.e

153 = (111) + (555) + (333).

Other Armstrong Numbers: 153, 370, 371, 407, 1634, 8208, 9474

# python program to check armstrong number

#Taking the input from user to check armstrong number


num=int(input("Enter the number to check armstrong number: "))

#Assigning the num value to arms


arms = num

#Finding the length of the number


length = len(str(num))
sum1 = 0

#Iterating the values to check armstrong number


while num != 0:
rem = num % 10
sum1 = sum1+(rem**length)
num = num//10

#Printing the result whether the given number is armstrong number or not
if arms == sum1:
print("The given number", arms, "is armstrong number")
else:
print("The given number", arms, "is not an armstrong number")

Output1 of the Python armstrong number program

Enter the number to check armstrong number: 153


The given number 153 is armstrong number

Output2 of the Python armstrong number program

Enter the number to check armstrong number: 123


The given number 123 is not an armstrong number

12) Write a Python program to check leap year.


Do you know what is the leap year, it occurs once every 4 years. It contains additional
days which makes a year 366 days.

#Python program to check whether the given year is leap year or not

# Function implementation to check leap year


def LeapYear(Year):
#Condition to check if the given year is leap year or not
if((Year % 400 == 0) or
(Year % 100 != 0) and
(Year % 4 == 0)):
print("The given Year is a leap year");
# Else it is not a leap year
else:
print ("The given Year is not a leap year")
# Taking an input year from user
Year = int(input("Enter the year to check whether a leap year or not: "))
# Printing the leap year result
LeapYear(Year)

Output1 of the Python leap year program

Enter the year to check whether a leap year or not: 2020


The given Year is a leap year

Output2 of the Python leap year program

Enter the year to check whether a leap year or not: 2021


The given year is not a leap year

13) Write a Python program to check prime


numbers.
A prime number is a positive integer p>1 that has no positive integer divisors other
than 1 and p itself.

Example Prime Numbers: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, ….

#Python program to check prime number

#Get the input to check whether a number is Prime or not

prime_num = int(input("Enter a number to check whether it is prime or not:


"))
if prime_num > 1:
for i in range(2, int(prime_num/2)+1):
if (prime_num % i) == 0:
print(prime_num, "is not a prime number")
break
else:
print(prime_num, "is a prime number")
else:
print(prime_num, "is not a prime number")

Output1 of Python program to check prime number

Enter a number to check whether it is prime or not: 7


7 is a prime number

Output2 of Python program to check prime number

Enter a number to check whether it is prime or not: 10


10 is not a prime number

14) Write a Python program to display a


multiplication table using for loop.
Here is the Python program to display the multiplication table of any number using for
loop.

#Python program to display multiplication table

#Get the number from the user for multipication table


tab_number = int(input ("Enter the number of your choice to print the
multiplication table: "))
#For loop to iterate the multiplication 10 times and print the table
print ("The Multiplication Table of: ", tab_number)
for count in range(1, 11):
print (tab_number, 'x', count, '=', tab_number * count)

The output of Python multiplication table

Enter the number of your choice to print the multiplication table: 10


The Multiplication Table of: 10
10 x 1 = 10
10 x 2 = 20
10 x 3 = 30
10 x 4 = 40
10 x 5 = 50
10 x 6 = 60
10 x 7 = 70
10 x 8 = 80
10 x 9 = 90
10 x 10 = 100

15) Write a Python program to swap two variables.


Python program to swap two variables.

# Take inputs from the user to swap the two variables


num1 = input('Enter the first variable: ')
num2 = input('Enter the second variable: ')

#Printing the numbers before swap


print('The value of num1 before swapping: {}'.format(num1))
print('The value of num2 before swapping: {}'.format(num2))

#Use temporary variable and swap the values


temp = num1
num1 = num2
num2 = temp

#Printing the numbers after swap


print('The value of num1 after swapping: {}'.format(num1))
print('The value of num2 after swapping: {}'.format(num2))

The output of the Python program to swap two numbers:

Enter the first variable: 5


Enter the second variable: 10

The value of num1 before swapping: 5


The value of num2 before swapping: 10

The value of num1 after swapping: 10


The value of num2 after swapping: 5

16) Write a Python program to check if a given


number is a Fibonacci number or not.
Here is the Python program to check the Fibonacci number:

#Python progam to check fibonacci number

# First two fibonacci terms


fib_nums = [0, 1]

number = int(input('Enter the number you want to check for fibonacci


number: '))

# Iterate fibonacci terms until the user number is reached


while fib_nums[-1] <= number:
fib_nums.append(fib_nums[-1] + fib_nums[-2])
#Printing the result whether the given number is fibonacci or not
if number in fib_nums:
print(f'Yes. {number} is a fibonacci number.')
else:
print(f'No. {number} is NOT a fibonacci number.')

Output1 of Python program to check Fibonacci number

Enter the number you want to check for fibonacci number: 8


Yes. 8 is a fibonacci number.

Output2 of Python program to check Fibonacci number

Enter the number you want to check for fibonacci number: 10


No. 10 is NOT a fibonacci number.

17) Write a Python program to find the area of a


circle.
The formula to find the area of the circle is: Area = pi * r2, where r is the radius of the
circle.

Here is the Python program to find the area of the circle.

# Python program to find area of a circle

def circ_Area(rad):
PI = 3.142
return PI * (rad*rad);
rad = float(input('Enter the radius of the circle: '))
print("Area of the circle is %.6f" % circ_Area(rad));

The output of the Python program is to find the area of a circle.

Enter the radius of the circle: 4


The area of the circle is 50.272000

18) Write a Python program to display the


calendar.
Python program to display the calendar.

#Python program to display calendar

import calendar
# Get the month and year from the users
year = int(input("Enter the year: "))
month = int(input("Enter the month: "))

# Displaying the calendar for the given year and month


print(calendar.month(year,month))

The output of the Python program to display the calendar.

Enter the year: 2022


Enter the month: 10
October 2022
Mo Tu We Th Fr Sa Su
12
3456789
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31

19) Write a Python program to find factorial of the


given number.
The factorial formual:

n! = n* (n-1) * (n-2) *……..1

4! = 4x3x2x1 = 24

5! = 5x4x3x2x1 = 120

# Python program to find factorial of a given number

import math
def check_Fact(num):
return(math.factorial(num))

num = int(input("Enter the number to find factorial:"))


fact = check_Fact(num)
print("Factorial of the number", num, "is", fact)

The output of the Python factorial program

Enter the number to find factorial:5


Factorial of the number 5 is 120

20) Write a Python program to print all prime


numbers in an interval.
Here is the Python program to display all the prime numbers within a range.

# Python program to print all prime number in an interval

def disp_Prime(num1, num2):


prime_List = []
for i in range(num1, num2):
if i == 0 or i == 1:
continue
else:
for j in range(2, int(i/2)+1):
if i % j == 0:
break
else:
prime_List.append(i)
return prime_List

# Driver program
starting_Num = int(input('Enter the starting range: '))
ending_Num = int(input('Enter the ending range: '))
lst = disp_Prime(starting_Num, ending_Num)
if len(lst) == 0:
print("There are no prime numbers in this range")
else:
print("The prime numbers in the given range are: ", lst)

The output of Python prime numbers display program

Enter the starting range: 5


Enter the ending range: 25
The prime numbers in this range are: [5, 7, 11, 13, 17, 19, 23]
Python Strings Interview Questions &
Answers

21) Write a Python Program to Find Vowels From a


String.
Python Program to Find Vowels From a String

This Python coding example returns the vowels “a e i o u” present in a string. This
Python program is useful when finding vowels, Let’s try this and see how it works.

#Python Program to Find Vowels From a String


#defining a function

def get_vowels(String):
return [each for each in String if each in "aeiou"]
get_string1 = "hello" # ['e', 'o']
get_string2 = "python is fun" # ['o', 'i', 'u']
get_string3 = "coding compiler" # ['o', 'i', 'o', 'i', 'e']
get_string4 = "12345xyz" # []

#Let's print vowels from the given strigns


#Vowels from first string
print("The Vowels Are: ",get_vowels(get_string1))

#Vowels from second string


print("The Vowels Are: ",get_vowels(get_string2))

#Vowels from third string


print("The Vowels Are: ",get_vowels(get_string3))

#Vowels from fourth string


print("The Vowels Are: ",get_vowels(get_string4))

The output of the above Python code:

The Vowels Are: [‘e’, ‘o’]


The Vowels Are: [‘o’, ‘i’, ‘u’]
The Vowels Are: [‘o’, ‘i’, ‘o’, ‘i’, ‘e’]
The Vowels Are: []

22) Write a Python Program to Convert Comma


Separated List to a String.
Python Program to Convert Comma Separated List to a String

In this Python coding example we use the join() method to convert comma separated
list to a string. Let’s try this Python program and see how it works.

# Python program to converting a comma separated list to a string

#comma seperated list


favorite_prog = ["Python", "SQL", "GO"]

#The join() method takes all items from the favorite_prog list and joins
them into one string.
print("What is your favorite programming language:", ",
".join(favorite_prog))

The output of the above Python code:

What is your favorite programming language: Python, SQL, GO

23) Write a Python Program to Capitalize the First


Letter of a String.
Python program to convert every first letter of the characters in a string to an
uppercase.

This Python coding example capitalizes every first letter of the characters in a string.
This Python program is useful when converting the first letter of a string to a capital
letter, Let’s try this and see how it works.

#Python Program to Capialize the First Letter of a String


#defining a capitalize function

def capitalize(String):
return String.title()

get_capital1 = "hello" # [Hello]


get_capital2 = "python programming" # [Python Programming]
get_capital3 = "python is easy to learn" # [Python Is Easy To Learn]

#Let's print capitalized string from the given strigns


#Capitalized string from first string
print("The Capitalized String Is: ",capitalize(get_capital1))

#Capitalized string from second string


print("The Capitalized String Is: ",capitalize(get_capital2))

#Capitalized string from third string


print("The Capitalized String Is: ",capitalize(get_capital3))
The output of the above Python code:

The Capitalized String Is: Hello


The Capitalized String Is: Python Programming
The Capitalized String Is: Python Is Easy To Learn

Python Implicit/Explicit Type Conversion


Interview Questions

24) Write a Python Program to Implicit Type


Conversion.
Python Program to Demonstrate Implicit Type Conversion.

This Python coding example explains implicit type conversion in Python. This Python
program is useful when working with different data types and conversions. Let’s try
this and see how it works.

#Implicit type casting example


get_num1 = 199 #int
get_num2 = 1.25 #float
get_num3 = get_num1 + get_num2 #int+float=?

print("Datatype of get_num1:",type(get_num1))
print("Datatype of get_num2:",type(get_num2))

print("The value of get_num3 is:",get_num3)


print("Datatype of get_num3:",type(get_num3))

#Implicit conversion - Python always converts smaller data types to larger


data types to avoid the loss of data.

The output of the above Python code:

Datatype of get_num1:
Datatype of get_num2:

The value of get_num3 is: 200.25


Datatype of get_num3: <class ‘float’>

25) What’s the Output of this Python program?


Let’s find out what’s the output of the below Python program.

#Let's find out what's the output of the below Python program.

#Implicit type casting example


num1 = 123
num2 = "456"

print("Data type of num_int:",type(num1))


print("Data type of num_str:",type(num2))
print("num1 data type is:",type(num1 + num2))

The output of the above Python code:

Data type of num_int:


Data type of num_str:
Traceback (most recent call last):
File “”, line 11, in
TypeError: unsupported operand type(s) for +: ‘int’ and ‘str’

Python is not able to convert string type to integer type implicitly. So we can see
TypeError in output.

26) Write a Python Program to Explicit Type


Conversion.
Python Program to Demonstrate Explicit Type Conversion.

Python coding example explains explicit type conversion in Python. This Python
program is useful when working with different data types and conversions. Let’s try
this Python code and see how it works.

#Python Program to Demonstrate Explicit Type Conversion

#Explicit type casting example


num1 = 123
num2 = "456"

print("Datatype of num1:",type(num1))
print("Datatype of num2 before Type Casting:",type(num2))

#Convertion of num2 from string(higher) to integer(lower) type using int()


function to perform the addition between num1 and num2.

num2 = int(num2)
print("Datatype of num2 after Type Casting:",type(num2))

num3 = num1 + num2

print("Sum of num1 and num2:",num3)


print("Data type of the num3:",type(num3))

The output of the above Python code:


Datatype of num1: <class ‘int’>
Datatype of num2 before Type Casting: <class ‘str’>

Datatype of num2 after Type Casting: <class ‘int’>

Sum of num1 and num2: 579


Data type of the num3: <class ‘int’>

Python Namespace Coding Interview


Questions

27) What’s the Output of this Python Namespace


program?
Python Namespace Program.

#Python Namespace Program Example

def outer_function():
num = 20

def inner_function():
num = 30
print('num =', num)

inner_function()
print('num =', num)

num = 10
outer_function()
print('num =', num)

The output of the above Python code:

Three different variables “num” are defined in separate namespaces and accessed
accordingly.

num = 30
num = 20
num = 10

28) What’s the Output of this Python program?


Python Namespace Program.

#Python Namespace Program Example

def outer_function():
global num
num = 20

def inner_function():
global num
num = 30
print('num =', num)

inner_function()
print('num =', num)

num = 10
outer_function()
print('num =', num)

The output of the above Python code:

All references and assignments are to the global ‘num’ due to the use of the keyword
‘global’.

num = 30
num = 30
num = 30

29) What does this do, and why should one


include the if statement?
Explain what the below Python program does.

if __name__ == "__main__":
print("Hello, World!")

Answer#

It’s boilerplate code that protects users from accidentally invoking the script when
they didn’t intend to. Here are some common problems when the guard is omitted
from a script:

If you import the guardless script in another script (e.g. import


my_script_without_a_name_eq_main_guard), then the latter script will trigger the
former to run at import time and use the second script’s command line arguments.
This is almost always a mistake.

If you have a custom class in the guardless script and save it to a pickle file, then
unpickling it in another script will trigger an import of the guardless script, with the
same problems outlined in the previous bullet.
Example Python Code:

Create the following two files:

# a.py

import b
# b.py

print("__name__ equals " + __name__)

if __name__ == '__main__':
print("if-statement was executed")
Now run each file individually.

Running python a.py:

$ python a.py
__name__ equals b
When a.py is executed, it imports the module b. This causes all the code
inside b to run. Python sets globals()['__name__'] in the b module to the
module's name, b.

#Running python b.py:

$ python b.py
__name__ equals __main__

if-statement was executed, when only the file b.py is executed, Python sets globals()
[‘name‘] in this file to “main“. Therefore, the if statement evaluates to True this time.

30) What does __all__ mean in Python?


Answer#

It’s a list of public objects of that module, as interpreted by import *. It overrides the
default of hiding everything that begins with an underscore.

Example Python Code:

Linked to, but not explicitly mentioned here, is exactly when __all__ is used. It is a list
of strings defining what symbols in a module will be exported when from <module>
import * is used on the module.

For example, the following code in a foo.py explicitly exports the symbols bar and baz:

__all__ = ['bar', 'baz']

waz = 5
bar = 10
def baz(): return 'baz'

# These symbols can then be imported like so:

from foo import *

print(bar)
print(baz)

# The following will trigger an exception, as "waz" is not exported by the


module
print(waz)

If the __all__ above is commented out, this code will then execute to completion, as
the default behavior of import * is to import all symbols that do not begin with an
underscore, from the given namespace.

Reference: https://docs.python.org/tutorial/modules.html#importing-from-a-package

NOTE: __all__ affects the from <module> import * behavior only. Members that are
not mentioned in __all__ are still accessible from outside the module and can be
imported with from <module> import <member>.

31) How to create a namespace package in


Python?
In Python, a namespace package allows you to spread Python code among several
projects. This is useful when you want to release related libraries as separate
downloads. For example, with the directories Package-1 and Package-2 in
PYTHONPATH,

Package-1/namespace/__init__.py
Package-1/namespace/module1/__init__.py
Package-2/namespace/__init__.py
Package-2/namespace/module2/__init__.py
the end-user can import namespace.module1 and import namespace.module2.

What’s the best way to define a namespace package so more than one Python
product can define modules in that namespace?

Answer#

On Python 3.3 you don’t have to do anything, just don’t put any __init__.py in your
namespace package directories and it will just work. On pre-3.3, choose the
pkgutil.extend_path() solution over the pkg_resources.declare_namespace() one,
because it’s future-proof and already compatible with implicit namespace packages.
Python 3.3 introduces implicit namespace packages.

This means there are now three types of objects that can be created by an import foo:

A module represented by a foo.py file


A regular package, represented by a directory foo containing an __init__.py file
A namespace package, represented by one or more directories foo without any
__init__.py files

32) How to create a Python namespace


(argparse.parse_args value)?
To interactively test my python script, I would like to create a Namespace object,
similar to what would be returned by argparse.parse_args(). The obvious way,

>>> import argparse


>>> parser = argparse.ArgumentParser()
>>> parser.parse_args()
Namespace()
>>> parser.parse_args("-a")
usage: [-h]
: error: unrecognized arguments: - a

Process Python exited abnormally with code 2 may result in Python repl exiting (as
above) on a silly error.

So, what is the easiest way to create a Python namespace with a given set of
attributes?

E.g., I can create a dict on the fly (dict([(“a”,1),(“b”,”c”)])) but I cannot use it as a
Namespace:

AttributeError: ‘dict’ object has no attribute ‘a’

Answer#

#You can create a simple class:

class Namespace:
def __init__(self, **kwargs):
self.__dict__.update(kwargs)

#and it'll work the exact same way as the argparse Namespace class when it
comes to attributes:

>>> args = Namespace(a=1, b='c')


>>> args.a
1
>>> args.b
'c'

#Alternatively, just import the class; it is available from the argparse


module:

from argparse import Namespace

args = Namespace(a=1, b='c')


As of Python 3.3, there is also types.SimpleNamespace, which essentially
does the same thing:

>>> from types import SimpleNamespace


>>> args = SimpleNamespace(a=1, b='c')
>>> args.a
1
>>> args.b
'c'

The two types are distinct; SimpleNamespace is primarily used for the
sys.implementation attribute and the return value of time.get_clock_info().

Further comparisons:

Both classes support equality testing; for two instances of the same class,
instance_a == instance_b is true if they have the same attributes with the same
values.
Both classes have a helpful __repr__ to show what attributes they have.
Namespace() objects support containment testing; ‘attrname’ in instance is true
if the namespace instance has an attribute namend attrname.
SimpleNamespace does not.
Namespace() objects have an undocumented ._get_kwargs() method that
returns a sorted list of (name, value) attributes for that instance. You can get
the same for either class using sorted(vars(instance).items()).
While SimpleNamespace() is implemented in C and Namespace() is
implemented in Python, attribute access is no faster because both use the same
__dict__ storage for the attributes. Equality testing and producing the
representation are a little faster for SimpleNamespace() instances.

33) What does __import__('pkg_resources').declare_namespace(__name__)

do?
In some init.py files of modules I saw such single line:

import(‘pkg_resources’).declare_namespace(name)

What does it do and why people use it? Suppose it’s related to dynamic importing and
creating namespace at runtime.

Answer#

Here are two things:


1) __import__ is a Python function that will import a package using a string as the
name of the package. It returns a new object that represents the imported package.
So foo = __import__(‘bar’) will import a package named bar and store a reference to
its objects in a local object variable foo.

2 From setup utils pkg_resources’ documentation, declare_namespace() “Declare[s]


that the dotted package name is a “namespace package” whose contained packages
and modules may be spread across multiple distributions.”

So __import__(‘pkg_resources’).declare_namespace(__name__) will import the


‘pkg_resources’ package into a temporary and call the declare_namespace function
stored in that temporary (the __import__ function is likely used rather than the import
statement so that there is no extra symbol left over named pkg_resources). If this
code were in my_namespace/__init__.py, then __name__ is my_namespace and this
module will be included in the my_namespace namespace package.

34) What exactly does “import *” import?


In Python, what exactly does import * import? Does it import __init__.py found in the
containing folder?

For example, is it necessary to declare from project.model import __init__, or is from


project.model import * sufficient?

Answer#

The “advantage” of from xyz import * as opposed to other forms of import is that it
imports everything (well, almost… [see (a) below] everything) from the designated
module under the current module. This allows using the various objects (variables,
classes, methods…) from the imported module without prefixing them with the
module’s name.

#For example

>>> from math import *


>>>pi
3.141592653589793
>>>sin(pi/2)
>>>1.0

35) Why is “import *” bad in Python?


It is recommended to not to use import * in Python.

Can you please share the reason for that?

Answer#

Because it puts a lot of stuff into your namespace (might shadow some other object
from the previous import and you won’t know about it).

Because you don’t know exactly what is imported and can’t easily find from which
module a certain thing was imported (readability).

Because you can’t use cool tools like pyflakes to statically detect errors in your code.

36) What are Python namespaces and explain how


to use namespaces & how this feature makes
programming better?
Answer#

Namespace is a way to implement scope.

In Java (or C) the compiler determines where a variable is visible through static scope
analysis.

In C, scope is either the body of a function or it’s global or it’s external. The compiler
reasons this out for you and resolves each variable name based on scope rules.
External names are resolved by the linker after all the modules are compiled.

In Java, scope is the body of a method function, or all the methods of a class. Some
class names have a module-level scope, also. Again, the compiler figures this out at
compile time and resolves each name based on the scope rules.

In Python, each package, module, class, function and method function owns a
“namespace” in which variable names are resolved. Plus there’s a global namespace
that’s used if the name isn’t in the local namespace.

Each variable name is checked in the local namespace (the body of the function, the
module, etc.), and then checked in the global namespace.

Variables are generally created only in a local namespace. The global and nonlocal
statements can create variables in other than the local namespace.

When a function, method function, module or package is evaluated (that is, starts
execution) a namespace is created. Think of it as an “evaluation context”. When a
function or method function, etc., finishes execution, the namespace is dropped. The
variables are dropped. The objects may be dropped, also.

37) Is it a good idea to use the class as a


namespace in Python?
Answer#

Yes, indeed. You can use Python classes strictly for namespacing as that is one of the
special things they can do and do differently than modules. It’s a lot easier to define a
class as a namespace inline in a file than to generate more files.
You should not do it without commenting on your code saying what it’s for. Python
classes come in a lot of different forms and purposes and this makes it difficult to
understand code you have not seen before.

A Python class used as a namespace is no less a Python class than one that meets the
perception of what a class is in other languages. Python does not require a class to be
instantiated to be useful. It does not require ivars and does not require methods. It is
fairly flexible.

Classes can contain other classes too.

Lots of people have their ideas about what is or isn’t Pythonic. But if they were all
worried about something like consistency, they’d push to have things like len() dir(),
and help() be a method of objects rather than a global function.

38) Is it possible to add an object to the global


namespace, for example, by using globals() or
dir()?
def insert_into_global_namespace(var_name, value):
globals()[var_name] = value

insert_into_global_namespace('my_obj', 'an object')


print(f'my_obj = {my_obj}')

#But this only works in the current module.

Answer#

#It is as simple as

globals()['var'] = "an object"


and/or

def insert_into_namespace(name, value, name_space=globals()):


name_space[name] = value

insert_into_namespace("var", "an object")

# Remark that globals is a built-in keyword, that is, 'globals' in


__builtins__.__dict__ evaluates to True.

39) What’s the python __all__ module level


variable for?
Answer#

It has two purposes:

Anybody who reads the source will know what the exposed public API is. It doesn’t
prevent them from poking around in private declarations but does provide a good
warning not to.

When using from mod import *, only names listed in __all__ will be imported. This is
not as important, in my opinion, because importing everything is a really bad idea.

40) Is it possible to call static method from within


class without qualifying the name in Python?
class MyClass:
@staticmethod
def foo():
print "hi"

@staticmethod
def bar():
MyClass.foo()

Is there a way to make this work without naming MyClass in the call? i.e. so I can just
say foo() on the last line?

Answer#

There is no way to use foo and get what you want. There is no implicit class scope, so
foo is either a local or a global, neither of which you want.

You might find classmethods more useful:

class MyClass:
@classmethod
def foo(cls):
print "hi"

@classmethod
def bar(cls):
cls.foo()

#This way, at least you don't have to repeat the name of the class.

Object-Oriented Python Coding Interview


Questions

41) What is the output of the below


(__class__.__name__) Object Oriented Python
code?
class Programming:
def name(self, name):
return name

p = Programming()
print(p.__class__.__name__)

#Output

Programming

42) What’s the output of the below


(type().__name__) Python code?
class Programming:
def name(self, name):
return name

p = Programming()
print(type(p).__name__)

#Output

Programming

43) What does super() do in Python? The


difference between super().__init__() and explicit
superclass __init__()?
#What's the difference between:

class Child(SomeBaseClass):
def __init__(self):
super(Child, self).__init__()
and:

class Child(SomeBaseClass):
def __init__(self):
SomeBaseClass.__init__(self)

I’ve seen super being used quite a lot in classes with only single inheritance. I can see
why you’d use it in multiple inheritance but am unclear as to what the advantages are
of using it in this kind of situation.

#Output

super() lets you avoid referring to the base class explicitly, which can be nice. But the
main advantage comes with multiple inheritance, where all sorts of fun stuff can
happen. See the standard docs on super if you haven’t already.

Note that the syntax changed in Python 3.0: you can just say super().__init__()
instead of super(ChildB, self).__init__() which IMO is quite a bit nicer.

What’s the difference?

SomeBaseClass.__init__(self)
means to call SomeBaseClass’s __init__. while

super().__init__()
means to call a bound __init__ from the parent class that follows SomeBaseClass’s
child class (the one that defines this method) in the instance’s Method Resolution
Order (MRO).

If the instance is a subclass of this child class, there may be a different parent that
comes next in the MRO.

Explained simply
When you write a class, you want other classes to be able to use it. super() makes it
easier for other classes to use the class you’re writing.

Good architecture allows you to postpone decision-making as long as possible.

super() can enable that sort of architecture.

When another class subclasses the class you wrote, it could also be inherited from
other classes. And those classes could have an __init__ that comes after this __init__
based on the ordering of the classes for method resolution.

Without super you would likely hard-code the parent of the class you’re writing (like
the example does). This would mean that you would not call the next __init__ in the
MRO, and you would thus not get to reuse the code in it.

If you’re writing your own code for personal use, you may not care about this
distinction. But if you want others to use your code, using super is one thing that
allows greater flexibility for users of the code.

Python 2 versus 3
This works in Python 2 and 3:

super(Child, self).__init__()
This only works in Python 3:

super().__init__()

It works with no arguments by moving up in the stack frame and getting the first
argument to the method (usually self for an instance method or cls for a class method
– but could be other names) and finding the class (e.g. Child) in the free variables (it is
looked up with the name class as a free closure variable in the method).

44) How to create static class variables or


methods in Python?
Answer#

Variables declared inside the class definition, but not inside a method are class or
static variables:

>>> class MyClass:


... i = 3
...
>>> MyClass.i
3

#This creates a class-level i variable, but this is distinct from any


instance-level i variable, so you could have

>>> m = MyClass()
>>> m.i = 4
>>> MyClass.i, m.i
>>> (3, 4)

This is different from C++ and Java, but not so different from C#, where a static
member can’t be accessed using a reference to an instance.

45) Why do Python classes inherit object?


Why does the following class declaration inherit from object?

class MyClass(object):

Answer#

#Python 3

class MyClass(object): = New-style class


class MyClass: = New-style class (implicitly inherits from object)

#Python 2

class MyClass(object): = New-style class


class MyClass: = OLD-STYLE CLASS

Explanation:

When defining base classes in Python 3.x, you’re allowed to drop the object from the
definition. However, this can open the door for a seriously hard-to-track problem…

Python introduced new-style classes back in Python 2.2, and by now old-style classes
are really quite old.

46) What is the purpose of the ‘self‘ parameter in


Python? Why is it needed?
#Consider this example:

class MyClass:
def func(self, name):
self.name = name

Answer#

The reason you need to use self. is because Python does not use a special syntax to
refer to instance attributes.

Python decided to do methods in a way that makes the instance to which the method
belongs be passed automatically, but not received automatically: the first parameter
of methods is the instance the method is called on.

That makes methods entirely the same as functions and leaves the actual name to
use up to you (although the self is the convention, and people will generally frown at
you when you use something else.) self is not special to the code, it’s just another
object.

Python could have done something else to distinguish normal names from attributes
— special syntax like Ruby has, or requiring declarations like C++ and Java do, or
perhaps something yet more different — but it didn’t.

Python’s all for making things explicit, making it obvious what’s what, and although it
doesn’t do it entirely everywhere, it does do it for instance attributes.

That’s why assigning to an instance attribute needs to know what instance to assign
to, and that’s why it needs self..

#Example: Let's say you have a class ClassA which contains a method
methodA defined as:

def methodA(self, arg1, arg2):


# do something
#and ObjectA is an instance of this class.

#Now when ObjectA.methodA(arg1, arg2) is called, python internally


converts it for you as:
ClassA.methodA(ObjectA, arg1, arg2)
#The self variable refers to the object itself.

47) What is the difference between old-style and


new-style classes in Python?
Answer#

Up to Python 2.1, old-style classes were the only flavor available to the user.

The concept of the (old-style) class is unrelated to the concept of type: if x is an


instance of an old-style class, then x.class designates the class of x, but type(x) is
always .

This reflects the fact that all old-style instances, independently of their class, are
implemented with a single built-in type, called an instance.

New-style classes were introduced in Python 2.2 to unify the concepts of class and
type. A new-style class is simply a user-defined type, no more, no less.

If x is an instance of a new-style class, then type(x) is typically the same as x.class


(although this is not guaranteed – a new-style class instance is permitted to override
the value returned for x.class).

The major motivation for introducing new-style classes is to provide a unified object
model with a full meta-model.

It also has a number of immediate benefits, like the ability to subclass most built-in
types, or the introduction of “descriptors”, which enable computed properties.

For compatibility reasons, classes are still old-style by default.

New-style classes are created by specifying another new-style class (i.e. a type) as a
parent class, or the “top-level type” object if no other parent is needed.

The behavior of new-style classes differs from that of old-style classes in a number of
important details in addition to what type returns.

Some of these changes are fundamental to the new object model, like the way special
methods are invoked. Others are “fixes” that could not be implemented before for
compatibility concerns, like the method resolution order in case of multiple
inheritances.

Python 3 only has new-style classes.

No matter if you subclass from the object or not, classes are new-style in Python 3.

Declaration-wise:

New-style classes inherit from an object, or from another new-style class.

class NewStyleClass(object):
pass

class AnotherNewStyleClass(NewStyleClass):
pass
Old-style classes don’t.

class OldStyleClass():
pass

Python 3 Note:

Python 3 doesn’t support old-style classes, so either form noted above results in a
new-style class.

48) How to call a parent class’s method from a


child class in Python?
Answer#

#Use the super() function:

class Foo(Bar):
def baz(self, **kwargs):
return super().baz(**kwargs)

#For Python < 3, you must explicitly opt in to using new-style classes and
use:

class Foo(Bar):
def baz(self, arg):
return super(Foo, self).baz(arg)

Example: super(type[, object-or-type])

Return a proxy object that delegates method calls to a parent or sibling class of type.
This is useful for accessing inherited methods that have been overridden in a class.

The search order is the same as that used by getattr() except that the type itself is
skipped.

class A(object): # deriving from 'object' declares A as a 'new-style-


class'
def foo(self):
print "foo"

class B(A):
def foo(self):
super(B, self).foo() # calls 'A.foo()'
myB = B()
myB.foo()

49) How to print instances of a class using print()


in Python?
When I try to print an instance of a class, I get an output like this:

>>> class Test():


... def __init__(self):
... self.a = 'foo'
...
>>> print(Test())
<__main__.Test object at 0x7fc9a9e36d60>

How can I define the printing behavior (or the string representation) of a class and its
instances?

For example, referring to the above code, how can I modify the Test class so that
printing an instance shows the value?

Answer#

>>> class Test:


... def __repr__(self):
... return "Test()"
... def __str__(self):
... return "member of Test"
...
>>> t = Test()
>>> t
Test()
>>> print(t)
member of Test

The __str__ method is what gets called happens when you print it, and the __repr__
method is what happens when you use the repr() function (or when you look at it with
the interactive prompt).

If no __str__ method is given, Python will print the result of __repr__ instead. If you
define __str__ but not __repr__, Python will use what you see above as the __repr__,
but still use __str__ for printing.

50) What is the difference between __init__ and


__call__?
I want to know the difference between __init__ and __call__ methods.

#For example:

class test:

def __init__(self):
self.a = 10

def __call__(self):
b = 20

Answer#

So, the __init__ method is used when the class is called to initialize the instance, while
the __call__ method is called when the instance is called.

Example:

The __init__ is used to initialize newly created object, and receives arguments used to
do that:

class Foo:
def __init__(self, a, b, c):
# ...

x = Foo(1, 2, 3) # __init__

#The __call__ implements function call operator.

class Foo:
def __call__(self, a, b, c):
# ...

x = Foo()
x(1, 2, 3) # __call__

Python OOP Coding Interview Questions

51) What are meta classes in Python?


Answer#

A metaclass is the class of a class. A class defines how an instance of the class (i.e. an
object) behaves while a metaclass defines how a class behaves. A class is an instance
of a metaclass.

While in Python you can use arbitrary callables for metaclasses (like Jerub shows), the
better approach is to make it an actual class itself. type is the usual metaclass in
Python. type is itself a class, and it is its own type. You won’t be able to recreate
something like type purely in Python, but Python cheats a little. To create your own
metaclass in Python you really just want to subclass type.

A metaclass is most commonly used as a class-factory. When you create an object by


calling the class, Python creates a new class (when it executes the ‘class’ statement)
by calling the metaclass.

Combined with the normal __init__ and __new__ methods, metaclasses, therefore,
allow you to do ‘extra things’ when creating a class, like registering the new class with
some registry or replacing the class with something else entirely.

When the class statement is executed, Python first executes the body of the class
statement as a normal block of code. The resulting namespace (a dict) holds the
attributes of the class-to-be.

The metaclass is determined by looking at the base classes of the class-to-be


(metaclasses are inherited), at the metaclass attribute of the class-to-be (if any) or
the __metaclass__ global variable. The metaclass is then called with the name, bases
and attributes of the class to instantiate it.

However, metaclasses actually define the type of a class, not just a factory for it, so
you can do much more with them. You can, for instance, define normal methods on
the metaclass.

These metaclass-methods are like class methods in that they can be called on the
class without an instance, but they are also not like class methods in that they cannot
be called on an instance of the class. type.__subclasses__() is an example of a
method on the type metaclass.

You can also define the normal ‘magic’ methods, like __add__, __iter__, and
__getattr__, to implement or change how the class behaves.

The __metaclass__ attribute

In Python 2, you can add a __metaclass__ attribute when you write a class (see next
section for the Python 3 syntax):

class Foo(object):
__metaclass__ = something…
[…]

If you do so, Python will use the metaclass to create the class Foo.

Metaclasses in Python 3

The syntax to set the metaclass has been changed in Python 3:

class Foo(object, metaclass=something):


i.e. the metaclass attribute is no longer used, in favor of a keyword argument in the
list of base classes.

The behavior of metaclasses however stays largely the same.

One thing added to metaclasses in Python 3 is that you can also pass attributes as
keyword-arguments into a metaclass, like so:

class Foo(object, metaclass=something, kwarg1=value1, kwarg2=value2):

52) What is the difference between


@staticmethod and @classmethod in Python?
Answer#

A staticmethod is a method that knows nothing about the class or instance it was
called on. It just gets the arguments that were passed, no implicit first argument. It is
basically useless in Python — you can just use a module function instead of a
staticmethod.

A classmethod, on the other hand, is a method that gets passed the class it was
called on, or the class of the instance it was called on, as first argument.

This is useful when you want the method to be a factory for the class: since it gets the
actual class it was called on as first argument, you can always instantiate the right
class, even when subclasses are involved.

Observe for instance how dict.fromkeys(), a classmethod, returns an instance of the


subclass when called on a subclass:

>>> class DictSubclass(dict):


... def __repr__(self):
... return "DictSubclass"
...
>>> dict.fromkeys("abc")
{'a': None, 'c': None, 'b': None}
>>> DictSubclass.fromkeys("abc")
DictSubclass
>>>

53) What is the meaning of single and double


underscore before an object name in Python?
Answer#

Single Underscore – In a class, names with a leading underscore indicate to other


programmers that the attribute or method is intended to be used inside that class.

However, privacy is not enforced in any way. Using leading underscores for functions
in a module indicates it should not be imported from somewhere else.
From the PEP-8 style guide:

_single_leading_underscore: weak “internal use” indicator. E.g. from M import * does


not import objects whose name starts with an underscore.

Double Underscore (Name Mangling)

From the Python docs:

Any identifier of the form __spam (at least two leading underscores, at most one
trailing underscore) is textually replaced with _classname__spam, where classname is
the current class name with leading underscore(s) stripped.

This mangling is done without regard to the syntactic position of the identifier, so it
can be used to define class-private instance and class variables, methods, variables
stored in globals, and even variables stored in instances. private to this class on
instances of other classes.

And a warning from the same page:

Name mangling is intended to give classes an easy way to define “private” instance
variables and methods, without having to worry about instance variables defined by
derived classes, or mucking with instance variables by code outside the class.

Note that the mangling rules are designed mostly to avoid accidents; it still is possible
for a determined soul to access or modify a variable that is considered private.

Example:

>>> class MyClass():


... def __init__(self):
... self.__superprivate = "Hello"
... self._semiprivate = ", world!"
...
>>> mc = MyClass()
>>> print mc.__superprivate
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: myClass instance has no attribute '__superprivate'
>>> print mc._semiprivate
, world!
>>> print mc.__dict__
{'_MyClass__superprivate': 'Hello', '_semiprivate': ', world!'}

54) What are the differences between type() and


isinstance() in Python?
Answer#

isinstance caters for inheritance (an instance of a derived class is an instance of a


base class, too), while checking for equality of type does not (it demands identity of
types and rejects instances of subtypes, AKA subclasses).

Normally, in Python, you want your code to support inheritance, of course (since
inheritance is so handy, it would be bad to stop code using yours from using it!), so
isinstance is less bad than checking identity of types because it seamlessly supports
inheritance.

#Using type:

import types

if type(a) is types.DictType:
do_something()
if type(b) in types.StringTypes:
do_something_else()

#Using isinstance:

if isinstance(a, dict):
do_something()
if isinstance(b, str) or isinstance(b, unicode):
do_something_else()

55) What is a mixin and why is it useful in Python?


Answer#

A mixin is a special kind of multiple inheritance. There are two main situations where
mixins are used:

1)You want to provide a lot of optional features for a class.


2) You want to use one particular feature in a lot of different classes.

For an example of number one, consider werkzeug’s request and response system. I
can make a plain old request object by saying:

from werkzeug import BaseRequest

class Request(BaseRequest):
pass

If I want to add accept header support, I would make that

from werkzeug import BaseRequest, AcceptMixin

class Request(AcceptMixin, BaseRequest):


pass

You might also like