Category: Python

  • What Is the Difference Between `deepcopy` and `shallowcopy` in Python?

    `deepcopy` creates a new object and recursively copies all objects found in the original. `shallowcopy` creates a new object but inserts references into it to the objects found in the original.

    Example:

    import copy
    
    original = [[1, 2, 3], [4, 5, 6]]
    shallow = copy.copy(original)
    deep = copy.deepcopy(original)
    
    shallow[0][0] = 100
    print(original)  # [[100, 2, 3], [4, 5, 6]]
    print(deep)      # [[1, 2, 3], [4, 5, 6]]
  • How Do You Use Python’s `multiprocessing.Queue` for Inter-Process Communication?

    `multiprocessing.Queue` allows safe exchange of data between processes. It supports inter-process communication.

    Example:

    from multiprocessing import Process, Queue
    
    def worker(queue):
        queue.put('Hello from process')
    
    queue = Queue()
    process = Process(target=worker, args=(queue,))
    process.start()
    process.join()
    
    print(queue.get())
  • Describe the Use of Metaclasses in Python

    Metaclasses in Python define how classes behave. They are the ‘classes of classes’ and allow you to customize class creation and inheritance.

    Example of a metaclass:

    class Meta(type):
        def __new__(cls, name, bases, dct):
            dct['greeting'] = 'Hello'
            return super().__new__(cls, name, bases, dct)
    
    class MyClass(metaclass=Meta):
        pass
    
    print(MyClass.greeting)  # Hello
  • How Do You Handle Exceptions with Custom Exception Classes in Python?

    Custom exception classes in Python help in defining specific error conditions. They improve error handling and debugging.

    Example:

    class MyError(Exception):
        def __init__(self, message):
            self.message = message
            super().__init__(self.message)
    
    try:
        raise MyError('Something went wrong')
    except MyError as e:
        print(e)
  • How Do You Implement and Use Decorators in Python?

    Decorators in Python are functions that modify the behavior of other functions or methods. They provide a way to wrap a function with additional functionality.

    Example of a decorator:

    def my_decorator(func):
        def wrapper():
            print('Something is happening before the function call.')
            func()
            print('Something is happening after the function call.')
        return wrapper
    
    @my_decorator
    def say_hello():
        print('Hello!')
    
    say_hello()
  • Describe the Process of Creating and Using Python Wheels for Package Distribution

    Python wheels are a distribution format for Python packages. They simplify the installation process.

    Creating a wheel:

    # Install wheel
    $ pip install wheel
    
    # Create wheel
    $ python setup.py bdist_wheel
  • Explain the Use of Context Managers in Python with Examples

    Context managers in Python handle resource management using the `with` statement. They ensure resources are properly acquired and released.

    Example of a context manager:

    class MyContextManager:
        def __enter__(self):
            print('Entering the context')
            return self
        def __exit__(self, exc_type, exc_val, exc_tb):
            print('Exiting the context')
    
    with MyContextManager() as cm:
        print('Inside the context')
    
  • How Do You Optimize I/O-Bound and CPU-Bound Tasks in Python?

    Optimizing I/O-bound tasks involves using asynchronous programming and efficient I/O operations. CPU-bound tasks can be optimized using multi-processing and efficient algorithms.

    Example for I/O-bound:

    import asyncio
    
    async def fetch_data():
        await asyncio.sleep(1)
        return 'data'
    
    # Example for CPU-bound
    from multiprocessing import Pool
    
    def compute(x):
        return x * x
    
    with Pool(5) as p:
        print(p.map(compute, range(10)))
  • How Does Garbage Collection Work in Python?

    Python uses garbage collection to manage memory. It relies on reference counting and cyclic garbage collection.

    Garbage collection example:

    import gc
    
    gc.collect()  # Forces garbage collection
  • Describe the Use of `functools.lru_cache` for Memoization

    `functools.lru_cache` caches the results of expensive function calls. It improves performance by avoiding redundant calculations.

    Example:

    from functools import lru_cache
    
    @lru_cache(maxsize=3)
    def fib(n):
        if n < 2:
            return n
        return fib(n-1) + fib(n-2)
    
    print(fib(10))