Showing posts with label Python. Show all posts
Showing posts with label Python. Show all posts

Thursday, December 11, 2025

Python FASTAPI - Impetus - 4 yoe - Nov 19, 2025


See All: Miscellaneous Interviews @ FloCareer

  1. Data Validation with Pydantic
    How does FastAPI leverage Pydantic for data validation, and why is it beneficial?
    
    FastAPI uses Pydantic models for data validation and serialization. Pydantic allows defining data schemas with Python type annotations, and it performs runtime data validation and parsing. For example, you can define a Pydantic model as follows:
    from pydantic import BaseModel
    
    class Item(BaseModel):
        name: str
        price: float
        is_offer: bool = None
    When a request is made, FastAPI automatically validates the request data against this model. This ensures that only correctly structured data reaches your application logic, reducing errors and improving reliability.
            
  2. Implementing Workflow Rules in FastAPI
    How would you implement workflow rules in a FastAPI application using a rules engine or library?
    Ideal Answer (5 Star)
    Implementing workflow rules in FastAPI can be done using libraries like Temporal or Azure Logic Apps. Temporal provides a framework for defining complex workflows in code with features like retries and timers. In FastAPI, you can define a workflow as a series of tasks executed in a specific order:
    from temporalio import workflow
    
    @workflow.defn(name='my_workflow')
    class MyWorkflow:
        @workflow.run
        async def run(self, param: str) -> str:
            result = await some_async_task(param)
            return result
    Using a rules engine allows for separation of business logic from application code, improving maintainability and scalability.
            
  3. Understanding Python Decorators
    Explain how decorators work in Python. Provide an example of a custom decorator that logs the execution time of a function.
    Ideal Answer (5 Star)
    Python decorators are a powerful tool that allows you to modify the behavior of a function or class method. A decorator is a function that takes another function as an argument and extends or alters its behavior. Decorators are often used for logging, enforcing access control and authentication, instrumentation, and caching.
    
    Here is an example of a custom decorator that logs the execution time of a function:
    
    ```python
    import time
    
    def execution_time_logger(func):
        def wrapper(*args, **kwargs):
            start_time = time.time()
            result = func(*args, **kwargs)
            end_time = time.time()
            print(f"Execution time of {func.__name__}: {end_time - start_time} seconds")
            return result
        return wrapper
    
    @execution_time_logger
    def sample_function():
        time.sleep(2)
        return "Function executed"
    
    sample_function()
    ```
    
    In this example, `execution_time_logger` is a decorator that prints the time taken by `sample_function` to execute. The `wrapper` function inside the decorator captures the start and end times and calculates the execution time, printing the result.
            
  4. Designing REST APIs with FastAPI
    How would you design a REST API using FastAPI for a simple online bookstore application? Describe the main components and endpoints you would create.
    Ideal Answer (5 Star)
    To design a REST API for an online bookstore using FastAPI, you would start by identifying the main resources: books, authors, and orders. Each resource would have its own endpoint. For example, '/books' would handle book-related operations. You would use FastAPI's path operation decorators to define routes like GET '/books' to retrieve all books, POST '/books' to add a new book, GET '/books/{id}' to get a specific book, PUT '/books/{id}' to update a book, and DELETE '/books/{id}' to remove a book. FastAPI's automatic data validation using Pydantic models ensures that the request and response bodies are correctly formatted.
            
  5. Problem Solving in Software Development
    Discuss a challenging problem you encountered in a Python FastAPI project and how you resolved it. What was your thought process and which tools or techniques did you use?
    Ideal Answer (5 Star)
    In a recent FastAPI project, I encountered a performance bottleneck due to synchronous database queries in a high-traffic endpoint. The solution involved refactoring the code to use asynchronous database operations with `asyncpg` and `SQLAlchemy`. My thought process was to first identify the problematic areas using profiling tools like cProfile and Py-Spy to pinpoint the slowest parts of the application. Once identified, I researched best practices for async programming in Python and implemented changes. I also set up load testing with tools like Locust to verify the improvements. This approach not only resolved the performance issue but also increased the overall responsiveness of the application.
            
  6. 
    Testing REST APIs
    Explain how you would test a REST API developed with FastAPI. What tools and strategies would you use?
    Ideal Answer (5 Star)
    Testing a REST API developed with FastAPI involves writing unit and integration tests to ensure the correctness and reliability of the API. You can use the 'pytest' framework for writing tests and 'httpx' for making HTTP requests in the test environment. FastAPI's 'TestClient' allows you to simulate requests to your API endpoints without running a live server. You should test various scenarios, including valid and invalid inputs, to ensure that your API behaves as expected. Mocking external services and databases can help isolate the API logic during testing.
            
  7. Asynchronous Background Tasks
    In FastAPI, implement an endpoint that triggers a background task to send an email. Assume the email sending is a mock function that prints to the console.
    Ideal Answer (5 Star)
    from fastapi import FastAPI, BackgroundTasks
    
    app = FastAPI()
    
    def send_email(email: str, message: str):
        print(f"Sending email to {email}: {message}")
    
    @app.post("/send-email/")
    async def send_email_endpoint(email: str, message: str, background_tasks: BackgroundTasks):
        background_tasks.add_task(send_email, email, message)
        return {"message": "Email sending in progress"}
    
  8. File Upload Endpoint
    Create an endpoint in FastAPI that allows users to upload files. The files should be saved to a directory on the server.
    Ideal Answer (5 Star)
    from fastapi import FastAPI, File, UploadFile
    import os
    
    app = FastAPI()
    UPLOAD_DIRECTORY = './uploads/'
    os.makedirs(UPLOAD_DIRECTORY, exist_ok=True)
    
    @app.post("/uploadfile/")
    async def create_upload_file(file: UploadFile = File(...)):
        file_location = os.path.join(UPLOAD_DIRECTORY, file.filename)
        with open(file_location, "wb") as f:
            f.write(await file.read())
        return {"info": f"file '{file.filename}' saved at '{UPLOAD_DIRECTORY}'"}
    
  9. Asynchronous Programming in FastAPI
    Discuss how FastAPI supports asynchronous programming and the advantages it provides.
    Ideal Answer (5 Star)
    FastAPI supports asynchronous programming natively, utilizing Python's async and await keywords. This allows the server to handle multiple requests simultaneously, making it highly efficient and capable of supporting a large number of concurrent users. Asynchronous programming is especially beneficial for I/O-bound operations, such as database queries and external API calls. For instance, an async function in FastAPI might look like this:
    @app.get('/async-endpoint')
    async def async_endpoint():
        await some_async_io_operation()
        return {"message": "Async operation complete"}
    This non-blocking nature can significantly improve the throughput of web applications.
    
  10. RATE CANDIDATE'S SKILLS
    Python
    FAST API
    REST API
    

Thursday, June 19, 2025

Interview Questions on "Arrays" - Ch 2 - Fluent Python

All Posts on Python

Interview Questions from "Fluent Python" Chapter 2: Sequences

Easy Questions

  1. What are the two main categories of sequences based on mutability?

  2. How do container sequences differ from flat sequences?

  3. What is the key advantage of list comprehensions over map/filter?

  4. How do you prevent list comprehensions from leaking variables (Python 2 vs. Python 3)?

  5. What is the purpose of collections.namedtuple?

  6. How does tuple unpacking work in Python?

  7. What does the * operator do in tuple unpacking (e.g., a, *rest = [1, 2, 3])?

  8. Why do Python slices exclude the last item (e.g., my_list[0:3])?

  9. How do you reverse a sequence using slicing?

  10. What is the difference between list.sort() and sorted()?


Medium Questions

  1. Explain how generator expressions save memory compared to list comprehensions.

  2. How would you use a list comprehension to generate a Cartesian product?

  3. When should you use bisect instead of the in operator for membership tests?

  4. How does bisect.insort maintain a sorted sequence efficiently?

  5. Why might array.array be preferable to list for numerical data?

  6. What is the purpose of memoryview in handling large datasets?

  7. How does deque.rotate() work, and when would you use it?

  8. What happens when you assign to a slice (e.g., my_list[2:5] = [20, 30])?

  9. Why does my_list = [[]] * 3 create a list with shared references?

  10. How does the key parameter in sorted() enable case-insensitive sorting?


Complex Questions

  1. Explain the behavior of a += b for mutable vs. immutable sequences.

  2. Why does t[2] += [50, 60] raise a TypeError but still modify a tuple’s mutable element?

  3. How does NumPy’s ndarray improve performance for numerical operations?

  4. Discuss the performance trade-offs of using deque vs. list for FIFO/LIFO operations.

  5. How can memoryview.cast() manipulate binary data without copying bytes?

  6. When would you use array.tofile() instead of pickle for saving numerical data?

  7. Explain how the key parameter in sorting functions leverages stability (e.g., Timsort).

  8. How does bisect support efficient table lookups (e.g., converting scores to grades)?

  9. Why is deque thread-safe for append/pop operations?

  10. Compare the performance of array.fromfile() vs. reading floats from a text file.


These questions cover core sequence operations, performance optimizations, and practical applications from the chapter, suitable for evaluating a candidate's depth of understanding.

Wednesday, June 18, 2025

What is the Python Data Model?

All Questions From This Chapter

The Python Data Model is the framework that defines how Python objects behave and interact with each other. It’s the foundation for all built-in behavior in Python, such as arithmetic operations, attribute access, iteration, string representation, and more.

🧩 Key Idea:

The Python Data Model is made up of special methods (a.k.a. "dunder" methods — methods with double underscores like __len__, __getitem__, __str__, etc.) that let you hook into the language’s syntax and built-in functions.


🔍 Examples of Special Methods and What They Enable:

MethodTriggered byUse Case
__len__len(obj)Make object countable
__getitem__obj[index]Indexing, slicing support
__iter__for item in objMake object iterable
__str__str(obj) or print(obj)Human-readable string representation
__repr__repr(obj)Debug-friendly object display
__call__obj()Make object behave like a function
__add__obj1 + obj2Operator overloading
__bool__if obj:Truthiness of an object

🎯 Why It Matters:

  • Lets you create custom classes that integrate seamlessly with Python’s built-in operations.

  • Powers frameworks like Django, Pandas, NumPy, and more.

  • Enables writing Pythonic, intuitive, and idiomatic code.


📘 Example:

python
class Word: def __init__(self, text): self.text = text def __len__(self): return len(self.text) def __str__(self): return f"Word: {self.text}" word = Word("Python") print(len(word)) # → 6 print(str(word)) # → Word: Python

📚 Summary:

The Python Data Model is what allows Python to be flexible, expressive, and powerful. It’s the secret sauce behind how user-defined classes can behave like built-in types.

Want to dive deeper into this? Luciano Ramalho's "Fluent Python" is an excellent book focused on this very concept.

Tags: Technology,Python,Interview Preparation,

What built-in function calls __abs__?

All Questions From This Chapter

The built-in function abs() in Python calls the __abs__ dunder method on an object.


✅ Example:

python
class Temperature: def __init__(self, value): self.value = value def __abs__(self): return abs(self.value) temp = Temperature(-40) print(abs(temp)) # Output: 40

🔍 What’s Happening:

When you write abs(temp), Python internally calls:

python
temp.__abs__()

This allows you to define custom behavior for abs() on your own classes.


🧠 Summary:

  • abs(obj) → Calls obj.__abs__()

  • You must implement __abs__ if you want your custom class to support abs()

This is part of Python’s data model that allows operator/function overloading.

Tags: Technology,Python,Interview Preparation,

What are "dunder" methods? Give an example.

All Questions From This Chapter

"Dunder" methods (short for "double underscore" methods) are special methods in Python that begin and end with double underscores (__), like __init__, __str__, and __len__. They’re also known as magic methods or special methods.

These methods are used to:

  • Customize the behavior of built-in operations

  • Enable operator overloading

  • Integrate your class with Python's core language features (like iteration, context managers, etc.)


Example:

python
class Book: def __init__(self, title): self.title = title def __str__(self): return f"Book: {self.title}" book = Book("Fluent Python") print(book) # Output: Book: Fluent Python
  • __init__: Initializes the object (like a constructor).

  • __str__: Defines what str(obj) or print(obj) returns.


🧠 Common Dunder Methods:

MethodPurpose
__init__Constructor (called on object creation)
__str__String representation (print(obj))
__repr__Debug representation (repr(obj))
__len__Length (len(obj))
__getitem__Indexing (obj[i])
__iter__Makes an object iterable
__eq__Equality (==)

Dunder methods let your objects behave like built-in types and integrate seamlessly with Python’s syntax and idioms.

Tags: Technology,Python,Interview Preparation,

What happens if you don’t implement __bool__ in a class?

All Questions From This Chapter

If you don’t implement __bool__ in a Python class, Python falls back to another method to determine the truthiness of your object.

🔁 Fallback Behavior:

  1. If __bool__ is not defined, Python checks for __len__.

  2. If __len__ is defined:

    • if obj: will evaluate to False if len(obj) == 0.

    • Otherwise, it evaluates to True.

  3. If neither __bool__ nor __len__ is defined, the object is considered truthy by default (i.e., True).


🔍 Example Without __bool__:

python
class Empty: def __len__(self): return 0 e = Empty() print(bool(e)) # False, because __len__ returns 0

🧱 Example With Neither:

python
class Thing: pass t = Thing() print(bool(t)) # True, because no __bool__ or __len__

✅ Summary

You define…bool(obj) is…
__bool__Uses the returned Boolean value
__len__, no __bool__False if len(obj) == 0, True otherwise
NeitherAlways True

🧠 Tip: Define __bool__ if you want explicit control over an object’s truthiness.

Tags: Technology,Python,Interview Preparation,