⁉️ Have you ever actually thought about what __name__ == "__main__" means? Most of us wrote it the first time because a tutorial said so. Today I was structuring a small backend service in Python. Nothing flashy yet, just defining the application entry point. And that familiar line showed up again: ✳️ if __name__ == "__main__": It’s simple, but it solves an important architectural problem. In Python, every file is a module. When you execute a file directly: ✳️ python app.py Python assigns: ✳️ __name__ = "__main__" But when the same file is imported somewhere else: ✳️ import app Now: ✳️ __name__ = "__app__" That difference determines whether certain blocks of code run or stay dormant. Why is that useful? Because it lets you: • Keep runtime logic separate from reusable logic • Prevent accidental execution when modules are imported • Define a clear entry point for your application • Expose objects (like a Flask/FastAPI app instance) without auto-starting the server Without this guard, importing a module could trigger execution unintentionally — which becomes messy in larger systems. It’s one of those small Python conventions that quietly enforces better structure. Not flashy. But foundational. #Python #BackendDevelopment #SoftwareEngineering #Architecture
Vineet Kushwaha’s Post
More Relevant Posts
-
We've been building a side project for a while now and thought it's time to share it. fuzzybunny is a fuzzy string matching library for Python, but the core is written in C++. That means you get the simplicity of a Python API with none of the performance overhead that comes with pure-Python alternatives. A few things that make it worth looking at: Speed: The Levenshtein implementation uses Myers' Bit-Parallel algorithm, which runs in O(N) for strings under 64 characters. Across benchmarks it's consistently 2-5x faster than comparable Python libraries. Parallel batch matching: `batch_match` runs across all available CPU cores via OpenMP, and since the C++ layer releases the GIL, it plays well with multithreaded Python code too. Multiple scorers, one interface: Levenshtein, Jaccard, Token Sort, Token Set, QRatio, WRatio, partial matching, and hybrid scoring where you can mix scorers with custom weights. You can also pass your own Python function as a scorer. Pandas and NumPy support: There's a `.fuzzy` accessor on Series objects so it fits into existing data pipelines without extra glue code. Type safe: Ships with PEP 561 stubs, so autocomplete and mypy work out of the box. `pip install fuzzybunny` Repo: https://lnkd.in/gtsSjFYE Pypi: https://lnkd.in/gdEuRTVX
To view or add a comment, sign in
-
-
Stop writing try/finally blocks. Use context managers instead. I see this pattern everywhere in Python codebases: connection = get_db_connection() try: result = connection.execute(query) finally: connection.close() Nothing wrong with it — until you have 15 resources to manage across your project. Here's the cleaner version with contextlib: from contextlib import contextmanager @contextmanager def db_connection(): conn = get_db_connection() try: yield conn finally: conn.close() with db_connection() as conn: result = conn.execute(query) Why this is better: → Resource cleanup logic lives in ONE place → You can't forget to close — it's automatic → Stack multiple with a single `with` statement → Works with async too (`@asynccontextmanager`) My favorite use case: temporary environment changes in tests. @contextmanager def override_settings(**kwargs): old = {k: getattr(settings, k) for k in kwargs} for k, v in kwargs.items(): setattr(settings, k, v) try: yield finally: for k, v in old.items(): setattr(settings, k, v) Small abstraction. Massive reduction in bugs. What's your favorite Python pattern that most people underuse? 👇 #Python #Programming #BackendDevelopment #SoftwareEngineering #CleanCode
To view or add a comment, sign in
-
Building a RAG app, primarily in Go. The pipeline is straightforward. Parse the PDF, create embeddings, upload to Postgres with pgvector, and use it for retrieval. Hit a wall with PDF parsing though. Go's support for it is nowhere close to what Python offers. So I split it, Python handles the parsing and writes the chunks to a file, and the Go ingest script picks it up from there and does the rest. Right tool for the right job. You don't have to go all in on one language for an entire pipeline. More on the tooling setup in the next post.
To view or add a comment, sign in
-
-
Most tutorials get this wrong. When building high-performance backend services in Python, it's easy to fall into patterns that feel familiar from languages like Java or C++. But Python offers a more elegant and efficient path. The 'Pythonic' way to think about building fast backend services with FastAPI is to embrace its asynchronous nature and leverage Python's built-in concurrency features. Instead of blocking operations, think in terms of non-blocking I/O. This allows your server to handle many requests simultaneously without getting bogged down. "Okay" Approach (Synchronous, Blocking): from fastapi import FastAPI import time app = FastAPI() @app.get("/process") async def processdatasync(): # Simulating a blocking I/O operation time.sleep(5) return {"message": "Data processed (slowly)"} "Best" Approach (Asynchronous, Non-blocking with async/await): from fastapi import FastAPI import asyncio app = FastAPI() @app.get("/process") async def processdataasync(): # Simulating a non-blocking I/O operation await asyncio.sleep(5) return {"message": "Data processed (quickly)"} The key difference is async def and await. This tells Python to run these functions concurrently, meaning the server isn't stuck waiting for one request to finish before starting another. Insight: FastAPI is built around Python's asyncio library. Using async and await for I/O-bound tasks is crucial for unlocking its high-performance potential. Fix: * Define your endpoints with async def. * Use await for any I/O operations (database calls, external API requests, file operations). * Consider using libraries that support asyncio for I/O (e.g., httpx for HTTP requests, asyncpg for PostgreSQL). FastAPI lets you build performant Python backends by thinking asynchronously, not by writing imperative, blocking code. #Python #CodingTips
To view or add a comment, sign in
-
-
🚀 "if __name__ == "__main__"" When I first started writing Python scripts, I often saw this line and ignored it: Later I realized — this small line controls how your code behaves when executed vs imported. 🔹 Every Python file has a special variable called "__name__". - When the file is run directly, Python sets: __name__ = "__main__" - When the file is imported into another file, Python sets: __name__ = "module_name" So this condition: if __name__ == "__main__": means: 👉 “Run the code inside this block only when the file is executed directly, not when it is imported.” --- 💡 Why is this powerful? - Keeps testing/demo code separate from reusable functions - Prevents unwanted execution when modules are imported - Helps create clean, production-ready Python modules --- 📌 Example: def add(a, b): return a + b if __name__ == "__main__": print(add(2, 3)) # runs only when executed directly When imported, only the function is available — the test code doesn’t run. --- Small Python habits like this make your code cleaner, reusable, and professional. #Python #Programming #CodingTips #SoftwareDevelopment #LearnPython
To view or add a comment, sign in
-
-
The sorted() vs list.sort() explanation in most Python content is technically correct and practically useless. "sort() modifies in place, sorted() returns a new list" — yes, fine. But that framing makes it sound like a style preference. In a backend service it is not. list.sort() modifies the actual object in memory. Every other piece of code holding a reference to that object now sees changed data. A cache entry you didn't mean to touch. A parameter the caller expected to be unchanged. An audit log that should have preserved insertion order. None of this crashes. It just silently produces wrong output until someone notices. I wrote a longer piece on this because I also wanted to correct something: a lot of Python articles claim CPython drops the GIL mid-sort so other threads can see a partially sorted list. That's only true when you're using a Python lambda as the key. With no key function, the GIL stays held. The mutation after the sort is the problem regardless, but the claim itself is wrong and worth fixing. Link in the comments. #Python #PythonDeveloper #SoftwareEngineering
To view or add a comment, sign in
-
-
💡 The moment Python file handling finally made sense to me When I first started working with files in Python, I was honestly a bit nervous. Opening a file felt risky. What if I overwrite something important? What if I forget to close the file? What if the file doesn’t even exist? At first I was doing everything manually opening files, remembering to close them, and hoping nothing went wrong. Then I discovered the with statement… and things became much simpler. The with statement automatically handles opening and closing the file for you. Even if something unexpected happens. Let’s say I want to store a simple to-do list in a file. tasks = ["Buy coffee", "Finish the report", "Call the client"] with open("todo.txt", "w") as file: for task in tasks: file.write(task + "\n") print("Tasks saved successfully.") The "w" mode creates the file and writes to it. ⚠️ One thing to remember: "w" will overwrite the file if it already exists. Now let’s read that file back. try: with open("todo.txt", "r") as file: content = file.read() print(content) except FileNotFoundError: print("The file doesn't exist yet.") Using try-except here prevents the program from crashing if the file is missing. So two small habits made file handling much safer for me: • Use with to manage files automatically • Use try-except to handle errors gracefully Small things like this make Python code cleaner and much less stressful to work with. Still learning something new every day. Curious what was the Python concept that confused you the most when you started? #Python #LearnToCode #CodingJourney #SoftwareDevelopment #DevCommunity
To view or add a comment, sign in
-
Pytest has become one of the most powerful and developer-friendly frameworks for testing in Python. Here are some key benefits that make it a preferred choice: 1. Simple and readable syntax Pytest allows you to write tests with plain Python functions. No need for complex class structures. 2. Automatic test discovery It automatically detects test files and functions based on naming conventions like test_*.py. 3. Powerful assertions No need to use special assertion methods. Simple assert statements provide detailed failure output. 4. Fixtures for reusable setup Fixtures help manage test setup and teardown efficiently, making your code cleaner and more maintainable. 5. Parameterization support You can run the same test with multiple inputs easily. 6. Rich plugin ecosystem Pytest supports many plugins for reporting, parallel execution, and more. Example: import pytest #Function to test def add(a, b): return a + b #Basic test def test_add(): assert add(2, 3) == 5 #Using fixture @pytest.fixture def sample_data(): return 10, 20 def test_add_with_fixture(sample_data): a, b = sample_data assert add(a, b) == 30 #Parameterized test @pytest.mark.parametrize("a, b, result", [ (1, 2, 3), (5, 5, 10), (0, 0, 0) ]) def test_add_param(a, b, result): assert add(a, b) == result Pytest helps you write scalable, maintainable, and clean test cases, making it an essential tool for modern Python testing. #pytest #automationtesting #python #softwaretesting
To view or add a comment, sign in
-
-
🚀 Just published a Python package to PyPI! pip install human-regex-lib Here's the problem it solves 👇 Every developer has been here: You need to validate an email, extract a phone number, or match a date format. You open a new tab. You Google "regex for email". You copy-paste some cryptic 50-character string and you have no idea if it's even correct. 😅 There had to be a better way. human-regex-lib lets you write regex using plain English keywords. No memorizing. No Googling. No cryptic symbols. Just chain simple words together and it builds the pattern for you behind the scenes. It's fully chainable, zero dependencies, and works on Python 3.8+. Fully open source — the package and all tests are on GitHub. 🔗 PyPI: https://lnkd.in/g_NGyzxN 🔗 GitHub: https://lnkd.in/g6swaa96 If you've ever copy-pasted regex without understanding it — this one's for you. Drop a ⭐ on GitHub if you find it useful, and let me know what patterns you'd want added next! #Python #OpenSource #PyPI #RegularExpressions #100DaysOfCode #BuildInPublic #SoftwareDevelopment
To view or add a comment, sign in
-
-
Ever wondered why FastAPI is so fast even though it's built with Python? Python is often considered slower than languages like Go or Node.js. Yet FastAPI can deliver performance that competes with them. So why is FastAPI so fast? The answer lies in the architecture underneath it. 1️⃣ Starlette (Lightweight ASGI framework) FastAPI is built on Starlette, which is an ASGI (Asynchronous Server Gateway Interface) framework. FastAPI uses Starlette for the core web functionality such as: • Routing • Middleware • WebSockets • Background tasks • Request/response handling Majorly performance is coming from the Starlette. 2️⃣ Pydantic for data validation FastAPI relies heavily on type hints in Python. These are used by Pydantic to automatically validate the incoming data. Pydantic v2 which is written in Rust, making validation extremely fast compared to traditional Python validation logic. 3️⃣ Uvicorn as the ASGI server FastAPI typically runs on Uvicorn, which is optimized for performance. Uvicorn uses: • uvloop — a high-performance event loop written in C • httptools — a fast HTTP parser also written in C FastAPI isn’t fast because Python suddenly became faster. It’s fast because of it underlying Architecture. Good architecture often matters more than the language itself.
To view or add a comment, sign in
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development