Q & A – Python Miscellaneous.


(1) What is Python? What are the benefits of using Python

What Is Python:

  • Python is a high-level, interpreted, general-purpose programming language.
  • Being a general-purpose language, it can be used to build almost any type of application with the right tools/libraries.
  • Additionally, python supports objects, modules, threads, exception-handling, and automatic memory management which help in modelling real-world problems and building applications to solve these problems.

Benefits Of Using Python:

  • Python is a general-purpose programming language that has a simple, easy-to-learn syntax that emphasizes readability and therefore reduces the cost of program maintenance.
  • Moreover, the language is capable of scripting, is completely open-source, and supports third-party packages encouraging modularity and code reuse.
  • Its high-level data structures, combined with dynamic typing and dynamic binding, attract a huge community of developers for Rapid Application Development and deployment

(2) What Is A Dynamically Typed Language?

  • Before we understand a dynamically typed language, we should learn about what typing is. 
  • Typing refers to type-checking in programming languages.
  • In a strongly-typed language, such as Python“1” + 2 will result in a type error since these languages don’t allow for “type-coercion” (implicit conversion of data types). On the other hand, a weakly-typed language, such as Javascript, will simply output “12” as result.

Type Checking:

  • Static  Data Types are checked before execution.
  • Dynamic Data Types are checked during execution.
  • Python is an interpreted language, executes each statement line by line and thus type-checking is done on the fly, during execution. Hence, Python is a Dynamically Typed Language.

(3) What Is An Interpreted Language?

  • An Interpreted language executes its statements line by line.
  • Languages such as Python, Javascript, R, PHP, and Ruby are prime examples of Interpreted languages.
  • Programs written in an interpreted language runs directly from the source code, with no intermediary compilation step.

(4) What Is PEP 8 And Why Is It Important?

  • PEP stands for Python Enhancement Proposal.
  • A PEP is an official design document providing information to the Python community, or describing a new feature for Python or its processes.
  • PEP 8 is especially important since it documents the style guidelines for Python Code. 
  • Apparently contributing to the Python open-source community requires you to follow these style guidelines sincerely and strictly.

(5) What Is Scope In Python?

  • Every object in Python functions within a scope.
  • A scope is a block of code where an object in Python remains relevant.
  • Namespaces uniquely identify all the objects inside a program. However, these namespaces also have a scope defined for them where you could use their objects without any prefix.
  • A few examples of scope created during code execution in Python are as follows:

Types Of Scope:

  • A local scope refers to the local objects available in the current function.
  • global scope refers to the objects available throughout the code execution since their inception.
  • module-level scope refers to the global objects of the current module accessible in the program.
  • An outermost scope refers to all the built-in names callable in the program. The objects in this scope are searched last to find the name referenced.
  • Note: Local scope objects can be synced with global scope objects using keywords such as global.

(6) What NameSpace In Python?

  • Name Space is the name register maintained by Python.
  • It will map all the variable names to its value.
  • This register will keep all the unique name lists in it.
  • When the user refers to any name, Python will go and search in this registry for the name.
  • NameSpace allows us to use the same name, by specifying the parent module name or class name.

Example

  • Let’s go through an example, a directory-file system structure in computers
  • Needless to say, one can have multiple directories having a file with the same name inside every directory
  • But one can get directed to the file, one wishes, just by specifying the absolute path to the file. 

Types Of NameSpace:

  • Local Namespace includes local names inside a function. the namespace is temporarily created for a function call and gets cleared when the function returns.
  • Global Namespace includes names from various imported packages/ modules that are being used in the current project. This namespace is created when the package is imported in the script and lasts until the execution of the script.
  • Built-in Namespace includes built-in functions of core Python and built-in names for various types of exceptions.
  • The lifecycle of a namespace depends upon the scope of objects they are mapped to. If the scope of an object ends, the lifecycle of that namespace comes to an end. Hence, it isn’t possible to access inner namespace objects from an outer namespace.

(7) What Are Lists And Tuples? What Is The Key Difference Between The Two?

  • Lists and Tuples are both sequence data types that can store a collection of objects in Python.
  • The objects stored in both sequences can have different data types.
  • Lists are represented with square brackets ['sara', 6, 0.19], while tuples are represented with parentheses ('ansh', 5, 0.97).
  • The key difference between the two is that while lists are mutabletuples on the other hand are immutable objects.
  •  This means that lists can be modified, appended or sliced on the go but tuples remain constant and cannot be modified in any manner

Example

my_tuple = ('sara', 6, 5, 0.97)
my_list = ['sara', 6, 5, 0.97]
print(my_tuple[0])     # output => 'sara'
print(my_list[0])     # output => 'sara'
my_tuple[0] = 'ansh'    # modifying tuple => throws an error
my_list[0] = 'ansh'    # modifying list => list modified
print(my_tuple[0])     # output => 'sara'
print(my_list[0])     # output => 'ansh'

(8) What Are The Common Built-in Data Types In Python?

  • Python doesn’t require data types to be defined explicitly during variable declarations.
  •  Python provides type() and isinstance() functions to check the type of these variables. These data types can be grouped into the following categories-

None Type:

  • None keyword represents the null values in Python. Boolean equality operation can be performed using these NoneType objects.

Numeric Type:

  • There are three distinct numeric types – integers, floating-point numbers, and complex numbers. Additionally, booleans are a sub-type of integers.

Sequence Types:

  • According to Python Docs, there are three basic Sequence Types – lists, tuples, and range objects.
  • Sequence types have the in and not in operators defined for their traversing their elements.
  • These operators share the same priority as the comparison operations.

Mapping Types:

  • A mapping object can map hashable values to random objects in Python.
  • Mappings objects are mutable and there is currently only one standard mapping type, the dictionary.

Set Types:

  • Currently, Python has two built-in set types – set and frozenset
  • set type is mutable and supports methods like add() and remove()
  • frozenset type is immutable and can’t be modified after creation.

(9) What Is Pass In Python?

  • The pass keyword represents a null operation in Python.
  • It is generally used for the purpose of filling up empty blocks of code which may execute during runtime but has yet to be written.
  • Without the pass statement in the following code, we may run into some errors during code execution.

Example:

def myEmptyFunc():
   pass
   
myEmptyFunc()   

# nothing happens

(10) What Are Modules And Packages In Python?

  • Python packages and Python modules are two mechanisms that allow for modular programming in Python.

Module:

  • Modules, in general, are simply Python files with a .py extension and can have a set of functions, classes, or variables defined and implemented.
  • They can be imported and initialized once using the import statement.
  • If partial functionality is needed, import the requisite classes or functions using from foo import bar.

Packages:

  • Packages allow for hierarchical structuring of the module namespace using dot notation.
  • As, modules help avoid clashes between global variable names, in a similar manner, packages help avoid clashes between module names.
  • Creating a package is easy since it makes use of the system’s inherent file structure.
  • So just stuff the modules into a folder and there you have it, the folder name as the package name.
  • Importing a module or its contents from this package requires the package name as a prefix to the module name joined by a dot.

(11)What Are Global, Protected And Private Attributes In Python?

(1) Global:

  • Global variables are public variables that are defined in the global scope.
  • To use the variable in the global scope inside a function, we use the global keyword.

Example-1:

x = 100

def add():
    y = 20
    result = x + y
    print(result)
    
add()
120

Note:

  • Here “X” is the Global variable.

Example-2: Using “global” Keyword.

def name():
    global name
    name = "Subrat Kumar Sahoo"
    
name()

print(f"My Name Is: {name}")
My Name Is: Subrat Kumar Sahoo

(2) Protected:

  • Protected attributes are attributes defined with an underscore prefixed to their identifier eg. _name.
  • Protected variables are those data members of a class that can be accessed within the class and the classes derived from that class.
  • They can still be accessed and modified from outside the class they are defined in but a responsible developer should refrain from doing so.

Example-1:

class Thing:
    def __init__(self, public: str, *, protected: str = "protected", private: str = "private"):
        self.public = public
        self._protected = protected
        self.__private = private

    def info(self) -> None:
        print(
            (
                f"This class has public attribute: {self.public}, "
                f"protected attribute: {self._protected}, "
                f"and private attribute: {self.__private}"
            )
        )

Output-1:

thing = Thing("public")

thing.info()
This class has public attribute: public, protected attribute: protected, and private attribute: private

Output-2:

print(thing.public)
public

Output-3:

print(thing._protected)
protected

Output-4:

print(thing.__private)
AttributeError                            Traceback (most recent call last)
Input In [8], in <cell line: 1>()
----> 1 print(thing.__private)

AttributeError: 'Thing' object has no attribute '__private'

(3) Private:

  • Private attributes are attributes with a double underscore prefixed to their identifier eg. __name.
  • They cannot be accessed or modified from the outside directly and will result in an AttributeError if such an attempt is made.
  • Private variables refer to those variable values that have the scope within a class,
  • i.e., these variables can be viewed and accessed within the class in which they have been declared and the classes outside that class cannot access them.

Example-1:

class Thing:
    def __init__(self, public: str, *, protected: str = "protected", private: str = "private"):
        self.public = public
        self._protected = protected
        self.__private = private

    def info(self) -> None:
        print(
            (
                f"This class has public attribute: {self.public}, "
                f"protected attribute: {self._protected}, "
                f"and private attribute: {self.__private}"
            )
        )

Output-1:

print(thing.__private)
AttributeError                            Traceback (most recent call last)
Input In [8], in <cell line: 1>()
----> 1 print(thing.__private)

AttributeError: 'Thing' object has no attribute '__private'

(12) What Is The Use Of Self In Python

  • self represents the instance of the class.
  • By using the “self”  we can access the attributes and methods of the class in Python.
  • It binds the attributes with the given arguments.
  • It does not have to be named self , you can call it whatever you like, but it has to be the first parameter of any function in the class.
  • Self is always pointing to the Current Object.

Output-1:

class car():
      
    # init method or constructor
    def __init__(self, model, color):
        self.model = model
        self.color = color
          
    def show(self):
        print("Model is", self.model )
        print("color is", self.color )
        

audi = car("audi a4", "blue")
ferrari = car("ferrari 488", "green")

audi.show()    
ferrari.show()
Model is audi a4
color is blue
Model is ferrari 488
color is green

Note:

  • By default, the object of the class is passed as an argument to every function of the class.
  • Hence to hold that object we need to have some variable as an argument declared in function parenthesis ( )
  • We need self because, if we have ‘n’ number of instances of the class, python will not know which class attribute belongs to which instance.
  • Hence by using the instance name and the attribute name like (self.name), it can easily access the variable.

(13) What Is __init__?

  • __init__ is a constructor method in Python and is automatically called to allocate memory when a new object/instance is created.
  • All classes have a __init__ method associated with them. It helps in distinguishing methods and attributes of a class from local variables.

Output-1:

class Student:
    def __init__(self, fname, lname, age, section):
        print("__init__ method has been called")
        self.firstname = fname
        self.lastname = lname
        self.age = age
        self.section = section
    def info(self):
        print(f'{self.firstname},{self.lastname},{self.age},{self.section}')
        
student = Student("Subrat",'Sahoo',32,'A1')
student.info()
__init__ method has been called
Subrat,Sahoo,32,A1

(14) What Is break, continue and pass In Python?

(1) Break:

  • The break statement terminates the loop immediately and the control flows to the statement after the body of the loop.
  • It comes out of the current loop.

Break Example:

lst = ['A', 'B', 'C', 'D']

for i in lst:
    print(i)
    if i == 'B':
        break
A
B

(2) Continue:

  • The continue statement terminates the current iteration of the statement, skips the rest of the code in the current iteration and the control flows to the next iteration of the loop.

Break Example:

lst = ['A', 'B', 'C', 'D']

for i in lst:
    if i == 'B':
        continue
    print(i)
A
C
D

(3) Pass:

  • If you have not decided on the implementation of the method yet, but want to declare the method only without its body.
  • At that time you can use the “pass” keyword.

Break Example:

def calculation():
    pass

calculation()

(15) What Is The Difference Between Python Arrays And Lists?

Array:

  • Arrays in Python can only contain elements of the same data types i.e., the data type of the array should be homogeneous.
  • It is a thin wrapper around C language arrays and consumes far less memory than lists.

List:

  • Lists in Python can contain elements of different data types i.e., data type of lists can be heterogeneous.
  • It has the disadvantage of consuming large memory.

Example-1: Array With Same Type

import array

a = array.array('i', [1, 2, 3])

for i in a:
    print(i, end=' ')
1 2 3

Example-2: Array With Different Type

a = array.array('i', [1, 2, 'string'])
TypeError                                 Traceback (most recent call last)
Input In [36], in <cell line: 1>()
----> 1 a = array.array('i', [1, 2, 'string'])

TypeError: an integer is required (got type str)

Example-3: List

a = [1, 2, 'string']

for i in a:
    print(i, end=' ')
a = [1, 2, 'string']

for i in a:
    print(i, end=' ')

(16) What Is Scope Resolution In Python?

  • Sometimes objects within the same scope have the same name but function differently.
  •  In such cases, scope resolution comes into play in Python automatically.
  • A few examples of such behaviour are:

Example-1

  • Python modules namely ‘math’ and ‘cmath’ have a lot of functions that are common to both of them – log10()acos()exp() etc.
  • To resolve this ambiguity, it is necessary to prefix them with their respective module, like math.exp() and cmath.exp().

Example-2

  • Consider the code below, an object temp has been initialized to 10 globally and then to 20 on the function call.
  • However, the function call didn’t change the value of the temp globally.
  • Here, we can observe that Python draws a clear line between global and local variables, treating their namespaces as separate identities.

Example

temp = 10  

def func():
    temp = 20   
    print(temp)
    
print('Before Function Call: ',temp)   

func() 

print('After Function Call: ',temp) 
Before Function Call:  10
20
After Function Call:  10

(17) What Are Decorators In Python?

  • Decorators are just the usual methods used to add extra functionalities to an existing method.
  • Python provides us with a way to add some extra functionality to an existing method, by using ‘Decorators’.
  • Decorators take a function as an argument and return a function as a return type.

Example-1

def decorate(func):
    def add(x,y):
        func(x,y)
        print('Addition:', x + y)
    return add
    
    
def numbers(x,y):
    print('Numbers Are:',x ,y)
    
dec = decorate(numbers)

dec(20,30)
Numbers Are: 20 30
Addition: 50

Example-2

def decorate(func):
    def add(x,y):
        func(x,y)
        print('Addition:', x + y)
    return add

@decorate
def numbers(x,y):
    print('Numbers Are:',x ,y)
    
numbers(20,30)
Numbers Are: 20 30
Addition: 50

Example-3

def lowercase_decorator(function):
    def wrapper():
        func = function()
        string_lowercase = func.lower()
        return string_lowercase
    return wrapper
    
def splitter_decorator(function):
    def wrapper():
        func = function()
        string_split = func.split()
        return string_split
    return wrapper
    
@splitter_decorator # this is executed next
@lowercase_decorator # this is executed first
def hello():
    return 'Hello World'
    
hello()
['hello', 'world']

Example-4

def names_decorator(function):
    def wrapper(arg1, arg2):
        arg1 = arg1.capitalize()
        arg2 = arg2.capitalize()
        string_hello = function(arg1, arg2)
        return string_hello
    return wrapper

@names_decorator
def say_hello(name1, name2):
    return 'Hello ' + name1 + '! Hello ' + name2 + '!'

say_hello('subrat', 'subhada')
'Hello Subrat! Hello Subhada!'

(18) What Are Dictionary and List Comprehensions?

  • Comprehension is the process of reducing the code length and being able to write it in a single statement.
  • Using comprehension you can use filtering, mapping, and apply conditional logic to the members of a sequence (such as lists, sets, dictionaries etc.) in a single line.
  • Comprehension allows us to filter the elements of the sequence and apply some conditional logic to an existing sequence, and it will return a new sequence.

Example-1: Performing mathematical operations on the entire list

my_list = [2, 3, 5, 7, 11]

squared_list = [i*i for i in my_list]

print(squared_list)

squared_dict = {i:i**2 for i in my_list}

print(squared_dict)
[4, 9, 25, 49, 121]
{2: 4, 3: 9, 5: 25, 7: 49, 11: 121}

Example-2: Performing conditional filtering operations on the entire list

my_list = [2, 3, 8, 7, 12]

even_list = [i for i in my_list if i%2 == 0]

print(even_list)

even_dict = {i:'Even' for i in my_list if i%2 == 0 }

print(even_dict)
[2, 8, 12]
{2: 'Even', 8: 'Even', 12: 'Even'}

Example-3: Combining Multiple Lists Into One

my_list = [[10,20,30],[40,50,60],[70,80,90]]

flattened = [j for lst in my_list for j in lst]

print(flattened)
[8, 10, 12]

Example-4: Flattening A Multi-Dimensional List

my_list = [[10,20,30],[40,50,60],[70,80,90]]

flattened = [j for lst in my_list for j in lst]

print(flattened)
[10, 20, 30, 40, 50, 60, 70, 80, 90]

(19) What Is Difference Between Expression & Statement

Expression:

  • An Expression is a sequence or combination of values, variablesoperators and function calls that always produces or returns a result value.
  • An expression evaluates to a value.
  • The evaluation of a statement does not change the state.
  • Evaluation of an expression always Produces or returns a result value.
  • Every expression can’t be a statement.
  • (a + 16) is an expression.

Statement:

  • A statement executes something.
  • The execution of a statement changes state.
  • Execution of a statement may or may not produces or displays a result value, it only does whatever the statement says.
  • Every statement can be an expression.
  • x = 3 (Statement)
  • print(x) (Statement)

(20) What Is Lambda In Python? Why Is It Used?

  • Lambda is an anonymous function in Python, that can accept any number of arguments, but can only have a single expression.
  • It is generally used in situations requiring an anonymous function for a short time period.
  • Lambda functions can be used in either of the two ways:

Example-1: Assigning lambda functions to a variable:

mul = lambda a, b : a * b

mul(5,4)
20

Example-2: Returning Lambda Functions Inside Another Function:

def myWrapper(n):
    return lambda a : a * n

mulFive = myWrapper(5)

mulFive(2)
10

(21) How Do You Copy An Object In Python?

  • In Python, the assignment statement (= operator) does not copy objects.
  • Instead, it creates a binding between the existing object and the target variable name
  • To create copies of an object in Python, we need to use the copy module.
  • Moreover, there are two ways of creating copies for the given object using the copy module –

Shallow Copy:

  • A shallow copy creates a new object which stores the reference of the original elements.
  • It means any changes made to the copy of the object reflects in the original object.

Example:

import copy  
x = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]  

z = copy.copy(x)  
  
x[2][2] = 'Hello' 

print(x) 

print(z)
[[1, 2, 3], [4, 5, 6], [7, 8, 'Hello']]
[[1, 2, 3], [4, 5, 6], [7, 8, 'Hello']]

Deep Copy:

  • A Deep Copy creates a new object and recursively adds the copies of nested objects present in the original elements.
  • In Deep Copy, any changes made to a copy of the object do not reflect in the original object.

Example:

import copy  
x = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]  

z = copy.deepcopy(x)  
  
x[2][2] = 'Hello' 

print(x) 

print(z)
[[1, 2, 3], [4, 5, 6], [7, 8, 'Hello']]
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

(22) What Is The Difference Between xrange And range In Python?

(23) What Is Lazy Evaluation In Python?

  • Lazy Evaluation is an evaluation strategy which delays the evaluation of an expression until its value is needed and also avoids repeated evaluations (From Wikipedia).
  • It’s usually considered a strategy to optimize your code.

Example: Strict Evaluation

  • For example, you have a simple expression sum = 1 + 2, Python would try to understand the real meaning of this expression and get the conclusion that sum = 3
  • This process is called Evaluation and it needs some sort of computation power.
  • In this case, the evaluation is done immediately, therefore it has another name: Strict Evaluation.

Example: Lazy Evaluation

  • On the other hand, we have a non-strict evaluation which is called Lazy Evaluation. 
  • The difference is that Lazy Evaluation will not immediately evaluate the expression but only does it when the outcome is needed. 
  • It’s a bit like a lazy student who only does the homework when it needs to be submitted to the teacher.
  • But being lazy here is not necessarily a bad thing, it can improve the efficiency of your code and save plenty of resources
  • Luckily, Python has silently applied Lazy Evaluation to many built-in functions in order to optimize your code

(24) How To Write Lazy Evaluation Function.

  • We write our own Lazy Evaluation function/class.
  • This helps us to extend the capability beyond the built-in functions.

Lazy function — Generator

def lazy_loading(items):
    for i in items:
        yield i ** 2
        
items = [i for i in range(10)]

for i in lazy_loading(items):
    print(i)
0
1
4
9
16
25
36
49
64
81

Lazy function — Decorator

  • Another common use case of customized Lazy Evaluation is the initialization of class properties.
  • When we initialize a class, certain properties might take a long time to calculate.
  • In the following example, the property cities takes a long time because it needs to invoke an API to get a list of city names.
  • Therefore, it would be a waste of time if we don’t actually need this value for some country objects.
  • A nice solution present in this blog is to create a decorator for such lazy properties so that the expensive operation will be done only if this property is needed.
  •  As you can see from the console output, cities property is called is printed out after we print out china.cities.
# Decorator Method
def lazy_property(fn):
    attr_name = '_lazy_' + fn.__name__

    @property
    def _lazy_property(self):
        if not hasattr(self, attr_name):
            setattr(self, attr_name, fn(self))
        return getattr(self, attr_name)
    return _lazy_property

class Country:
    def __init__(self, name, capital):
        self.name = name
        self.capital = capital

    @lazy_property
    def cities(self):
        # expensive operation to get all the city names (API call)
        print("cities property is called")
        return ["city1", "city2"]
    
china = Country("china", "beijing")
print(china.capital)
print(china.cities)
beijing
cities property is called
['city1', 'city2']

(25) What Is Pickling And Unpickling?

  • Python library offers a feature – serialization out of the box.
  • Serializing an object refers to transforming it into a format that can be stored, so as to be able to deserialize it, later on, to obtain the original object.
  • Here, the pickle module comes into play.

Pickling:

  • Pickling is the name of the serialization process in Python.
  • Any object in Python can be serialized into a byte stream and dumped as a file in the memory.
  • The process of pickling is compact but pickle objects can be compressed further.
  • Moreover, the pickle keeps track of the objects it has serialized and the serialization is portable across versions.
  • The function used for the above process is pickle.dump()
pickle.dump(obj, file, protocol=None, *, fix_imports=True, buffer_callback=None)
  • Write the pickled representation of the object obj to the open file object file.

Unpickling:

  • Unpickling is the complete inverse of pickling.
  • It deserializes the byte stream to recreate the objects stored in the file and loads the object to memory.
  • The function used for the above process is pickle.load().
pickle.load(file, *, fix_imports=True, encoding='ASCII', errors='strict', buffers=None)
  • Read the pickled representation of an object from the open file object file and return the reconstituted object hierarchy specified therein. 

Example: Dumping A Python Object

import pickle

student_names = ['Subrat','Arpita','Subhada','Sonali','Abhispa']

with open('pickle.txt','wb') as file:
    pickle.dump(student_names, file)

Example: Loading The Python Object

with open('pickle.txt', 'rb') as file:
    name_list = pickle.load(file)
    print(name_list)
['Subrat', 'Arpita', 'Subhada', 'Sonali', 'Abhispa']

(26) What Are Generators In Python?

  • In Python, a generator is a function that returns an iterator that produces a sequence of values when iterated over.
  • Generators are useful when we want to produce a large sequence of values, but we don’t want to store all of them in memory at once.

Example-1:

def my_generator():
    yield 'a'
    yield 'b'
    yield 'c'
    yield 'd'

for i in my_generator():
    print(i)
    
a
b
c
d

Example-2:

def my_generator():
    yield 'a'
    yield 'b'
    yield 'c'
    yield 'd'

g = generator()
print(type(g))

print(next(g))
print(next(g))
print(next(g))
print(next(g))
    
<class 'generator'>
a
b
c
d
---------------------------------------------------------------------------
StopIteration                             Traceback (most recent call last)
Input In [48], in <cell line: 8>()
      6 print(next(g))
      7 print(next(g))
----> 8 print(next(g))

StopIteration: 

Example-2:

def my_generator(num):
    for i in range(num):
        yield i
    
for i in my_generator(5):
    print(i)
0
1
2
3
4

(27) Python Generator Expression.

  • We have to use round brackets instead of square brackets to create a generator everything else is similar to List comprehension.

Example-1:

nums = [2, 3, 4, 5, 6]
square_num = (x**2 for x in nums)

print(square_num)
for num in square_num:
    print(num)
<generator object <genexpr> at 0x0000020AC665EC10>
4
9
16
25
36

(27) What is PYTHONPATH in Python?

  • PYTHONPATH is an environment variable which you can set to add additional directories where Python will look for modules and packages.
  • This is especially useful in maintaining Python libraries that you do not wish to install in the global default location.
  • It is typically used by developers to ensure that their code can find the required Python libraries when it is run.

Is SYS path the same as Pythonpath?

  • The SYS path is a list of directories that Python interprets to search for when it starts up. 
  • The Pythonpath is a list of directories that the Python interpreter will search for when it tries to resolve a module name. 

(28) What Is The Use Of help() and dir() Functions?

help():

  • help() function in Python is used to display the documentation of modules, classes, functions, keywords, etc.
  • If no parameter is passed to the help() function, then an interactive help utility is launched on the console.

Syntax:

help([object])

Example:

help(print)
Help on built-in function print in module builtins:

print(...)
    print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
    
    Prints the values to a stream, or to sys.stdout by default.
    Optional keyword arguments:
    file:  a file-like object (stream); defaults to the current sys.stdout.
    sep:   string inserted between values, default a space.
    end:   string appended after the last value, default a newline.
    flush: whether to forcibly flush the stream.

dir():

  • The dir() function returns all properties and methods of the specified object, without the values.

  • This function will return all the properties and methods, even built-in properties which are the default for all objects.

Syntax:

dir(object)

Example:

class car():
      
    # init method or constructor
    def __init__(self, model, color):
        self.model = model
        self.color = color
          
    def show(self):
        print("Model is", self.model )
        print("color is", self.color )
        

audi = car("audi a4", "blue")
ferrari = car("ferrari 488", "green")

dir(audi)
['__class__',
 '__delattr__',
 '__dict__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__gt__',
 '__hash__',
 '__init__',
 '__init_subclass__',
 '__le__',
 '__lt__',
 '__module__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 '__weakref__',
 'color',
 'model',
 'show']

(29) What Is The Difference Between .py and .pyc Files?

  • .py files contain the source code of a program.
  • Whereas, the .pyc file contains the bytecode of your program.
  • We get bytecode after compilation of the .py file (source code).
  • .pyc files are not created for all the files that you run. It is only created for the files that you import.
  • Before executing a Python program python interpreter checks for the compiled files.
  • If the file is present, the virtual machine executes it.
  • If not found, it checks for .py file. If found, compiles it to .pyc file and then python virtual machine executes it.
  • Having .pyc file saves you the compilation time.
  • The .pyc files are stored in the same directory as the corresponding .py files, and have the same name as the .py files, except with a .pyc extension instead of .py.

(30) How Are Arguments Passed By Value Or By Reference In python?

  • Pass by value: A copy of the actual object is passed. Changing the value of the copy of the object will not change the value of the original object.
  • Pass by reference: Reference to the actual object is passed. Changing the value of the new object will change the value of the original object.
  • In Python, arguments are passed by reference, i.e., reference to the actual object is passed.

Leave a Reply

Your email address will not be published. Required fields are marked *