Stop Guessing: Literal vs. Enum in Python Pydantic Ever wondered whether to use Literal or a str Enum for your validation models? Both restrict input, but they serve different masters. Here is the "Cheat Sheet" for your next PR: 🔹 Use Literal when... - The scope is tiny: You only need to restrict a field in one specific model. - Simplicity is king: You don’t want the overhead of a new class for 2 or 3 static values. - One-off validation: "Is this 'asc' or 'desc'?" Example: status: Literal["open", "closed"] 🔸 Use Enum when... - Reusability matters: You need the same options in your Database, your API, and your logic. - Logic is attached: You need to map values to other data (like duration limits or price multipliers). - Refactoring safety: Changing "days" to "Days" in one class updates your entire codebase instantly. - IDE Power: You want full autocomplete and to avoid "Magic Strings" everywhere. 💡 The Pro-Tip: If your project is a FastAPI app, always lean toward Enums. They generate much richer OpenAPI (Swagger) documentation, providing your frontend team with a clear dropdown of choices instead of a raw string field. Which one do you find yourself reaching for most often? 👇 #Python #Pydantic #FastAPI #CodingTips #BackendDevelopment
Pydantic Literal vs Enum: Choosing the Right Validation Tool
More Relevant Posts
-
🚀 LeetCode Practice 📌 Problem: Number of Steps to Reduce a Number in Binary Representation to One 🔗 LeetCode Problem #1404 🧠 Problem Statement Given a binary string s, return the number of steps required to reduce it to "1" using: ✅ If the number is even → divide it by 2 ✅ If the number is odd → add 1 It is guaranteed that we can always reach "1". 🔎 Example Input: s = "1101" Output: 6 Explanation: 13 (1101) → +1 → 14 14 → /2 → 7 7 → +1 → 8 8 → /2 → 4 4 → /2 → 2 2 → /2 → 1 💡 Key Insight The length of s can be up to 500 bits, so converting directly to an integer might not be ideal in some languages. Instead, we: Traverse from right to left Simulate division and addition Maintain a carry variable Count operations efficiently ⚡ Optimized Approach (Greedy + Carry Handling) 🔥 Core Observations If last bit is '0' → number is even → 1 step (divide) If last bit is '1' → number is odd → 2 steps (add 1 + divide) Handle carry propagation carefully 🧑💻 Python Implementation (O(n) Time | O(1) Space) class Solution: def numSteps(self, s: str) -> int: steps = 0 carry = 0 # Traverse from right to left (ignore MSB) for i in range(len(s) - 1, 0, -1): bit = int(s[i]) # If bit + carry == 1 → odd if bit + carry == 1: steps += 2 carry = 1 else: steps += 1 return steps + carry 📊 Complexity Analysis ⏱ Time Complexity: O(n) 📦 Space Complexity: O(1) Where n is the length of the binary string. #LeetCode #ProblemSolving #Python #DSA #CodingInterview #BitManipulation #TechGrowth
To view or add a comment, sign in
-
-
In plain English, "and" and "or" are just connective words. In Python, they are strict gatekeepers. 🧐 ⠀ Confusing them is the easiest way to break the logic of your application. ⠀ Let's look at a real-world example: Going to the cinema. 🍿 ⠀ 🎬 The "Flexible" Approach (OR): Imagine regular entry to a movie. You write: `if has_paper_ticket OR has_digital_app:` ⠀ The `or` operator is chill. It opens the door if *either* condition is met. Did you forget your paper ticket but have your phone? No problem. You're in. ⠀ 🔞 The "Strict" Approach (AND): Now imagine entry to an age-restricted screening (18+). You write: `if has_ticket AND is_over_18:` ⠀ The `and` operator is the strict manager. It demands *both* requirements be met simultaneously. Have a ticket but forgot your ID? You aren't getting in. ⠀ Logical operators aren't just syntax; they define the rules of your digital world. ⠀ Don't accidentally lock your users out (or let the wrong ones in) because you chose the wrong conjunction. ⠀ We turn boring Python documentation into a friendly, 3-minute daily habit. ☕ ⠀ 👇 Subscribe to the website for free: https://lnkd.in/ducXvs-y ⠀ #Python #Logic #CodingTips #SoftwareDevelopment #LearnToCode #PyDaily
To view or add a comment, sign in
-
-
📢 532 downloads in 3 days. No marketing. Open Source. No VC money.🚀 Just a Python framework that gets out of your way. We built SynapseKit because debugging LLM apps was taking longer than building them. Too many layers. Too much magic. Too little control over what was actually happening. So we started over. From scratch. ⚡ Async-native. Streaming-first. 2 dependencies. Code you can read on a Monday morning without coffee. What's inside: 🔌 13 LLM providers behind one interface :swap models in one line 🔍 10 retrieval strategies: RAG Fusion, CRAG, Ensemble, Self-Query 🔀 Graph workflows with human-in-the-loop and SSE streaming 🛠️ 16 tools, 12 loaders, 4 memory backends ✅ 540 tests passing No hidden chains. No magic. Just code that does what you think it does. If you're building LLM apps in Python and want something you can actually debug: 📦 pip install synapsekit[openai] 🔗 https://lnkd.in/d2fGSPkX #Python #LLM #RAG #OpenSource #AI #MLEngineering #MachineLearning #Developers #SoftwareEngineering #AgenticAI
To view or add a comment, sign in
-
When we debug our own and students' issues, things get connected slowly. I was trying to figure out the reason behind 𝐢𝐩𝐲𝐰𝐢𝐝𝐠𝐞𝐭𝐬 issue that I face every week. Sometimes, when we import directly either in Colab on Google's server or Jupyter locally, we face some interactive visuals to be missing. 𝐢𝐩𝐲𝐰𝐢𝐝𝐠𝐞𝐭𝐬 is something which is used for direct interaction with plots instead of visualization. It makes this possible through simple UI controls like sliders, dropdowns, buttons, etc. But, one thing to take care of is the way of handling this is slightly different in both 𝐆𝐨𝐨𝐠𝐥𝐞 𝐂𝐨𝐥𝐚𝐛 & 𝐉𝐮𝐩𝐲𝐭𝐞𝐫 𝐍𝐨𝐭𝐞𝐛𝐨𝐨𝐤. A notebook actually has two sides working together. The Python kernel, which runs our code in the backend. Then, the browser displays the output in the frontend. With 𝐢𝐩𝐲𝐰𝐢𝐝𝐠𝐞𝐭𝐬, Python creates the widget, but the browser (through JavaScript) is responsible for drawing/displaying the slider or button we actually see. So, if that frontend support is not properly defined, the widget gets created somehow, but in most cases, Python either throws errors or doesn't show the actual visual. In Google Colab, we just need to enable the widget manager (both installing and activating), whereas in a local Jupyter, we usually need to install and enable the widget extension. So, it's like same issue, the same process to solve it, but slightly different enviroment setup. For me, this was a small, minor challenge but it can be a reminder. For more information, check here: https://lnkd.in/ehpE6Nt8 and https://lnkd.in/eEHY3THd #python #ipywidgets
To view or add a comment, sign in
-
-
Python is like that high school ex you run into: you remember the good times, but five minutes in, you're reminded exactly why you moved on. 🐍 After being fully immersed in the TypeScript ecosystem, jumping back into a Python project felt... weird. Going from the safety of strict typing and seamless ESM imports back into the land of manual labor was a wake-up call. Here is the "Welcome Back" package I didn't ask for: The Venv Ritual: Why am I still manually creating and activating virtual environments in 2026? It feels like hand-cranking a car engine just to go to the grocery store. 🛠️ The "Invisible" Packages: That moment when uv list shows the package is there, the interpreter is set correctly, but Python still insists it doesn't exist. Ghosting at its finest. 👻 Manual Everything: Coming from a world where the tooling feels like it has your back, Python's setup feels like it's actively trying to trip you up over a stray .env or a path mismatch. Don't get me wrong, Python is a powerhouse for AI and Data Science, but the developer experience gap is becoming hard to ignore. When you're used to the speed of tools like Bun or the reliability of TS types, those "silly" import errors feel a lot less like a minor bug and a lot more like a tax on your productivity. Has anyone else felt this "syntax shock" lately, or have I just been spoiled by the TS ecosystem? #SoftwareEngineering #Python #TypeScript #WebDevelopment #FullStack #CodingLife
To view or add a comment, sign in
-
-
Python In super() function: The super() function is used to called method from the parent base class inheritance child class it helping method overriding constructor child in avoid directly using parent class name. class parent():(class is keyword, parent is class name) def __init__(self,name):(def is keyword, init constructor it is used in mutiple times in calling function name,because override the method) self.name=name(self is method and name is argument) print("parent constructor")(print bulding statement) class child(parent):we can create another classs child in inheritance parent class) def __init__(self,name,age):(self is method we can't used in function raise an error) super().__init__(name)#super function in directly override the parent class slef.age=age print("child constructor") obj1=child("bhanu",22)#obj1 is creating a object,we can call child class name) print(obj1.name)(print statement display the argument values) print(obj1.age) output: parent constructor child constructor bhanu 22 Pooja Chinthakayala Mam,Saketh Kallepu Sir,Uppugundla Sairam Sir.
To view or add a comment, sign in
-
Simplify Currency Formatting with Sepyrate 1.1.0! 🚀 Hey Pythonistas! 🐍 Formatting numbers for global markets can be a localized headached. Not everyone uses 1,000.00. Some need 1.000,00, others 1 000.00, or even 1'000.00 and 1_000.00. If you’ve ever built a Django or Flask app for international markets, you know what I'm talking about. I’ve just released a new version of Sepyrate, a lightweight utility designed to handle these separations cleanly without fighting with `locale` settings or complex regex. What’s new? ✅ Refactored `Decimal` handling for high-precision financial data. ✅ Clean, unified API for `int`, `float`, `numpy.float32`, `numpy.float64`, and `Decimal`. Examples (1) Formatting floating-point numbers ``` from sepyrate import digit_separation amount = 12000.56 # Using a dot for thousands and a comma for decimals print(digit_separation(amount, tsep='.', dsep=',')) # Output: '12.000,56' ``` (2) Using it in your Django Models Instead of messy template tags, you can keep your logic in the model for clean, reusable code: ``` from django.db import models from sepyrate import digit_separation class Invoice(models.Model): total_amount = models.DecimalField(max_digits=12, decimal_places=2) @property def formatted_total(self): # Displays 1.250.000,00 return digit_separation(self.total_amount, tsep='.', dsep=',') ``` Check it out on PyPI: https://lnkd.in/gUrZ4BcD #Python #Django #WebDevelopment #OpenSource #SoftwareEngineering #PythonProgramming
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
-
-
Most beginners never move past the Python shell. They run one line at a time. They never write a real program. They never take input. They never see a full flow. Here’s how to cross that gap in one go: 1. One .py file – not the shell 2. Ask the user – input() 3. Convert types – int(), float() so math works 4. Do the math – expressions and variables 5. Show the result – print() Example: Area of rectangle in a few lines: length = int(input("Enter length: ")) breadth = int(input("Enter breadth: ")) area = length * breadth print("Area =", area) That’s a complete program. No magic. No frameworks. Just: input → process → output. I wrote a full beginner’s guide that walks through: What makes a program “complete” Your first program (area of rectangle), step by step Using input() and type conversion Using expressions and print() Formatting and structure More examples (circle area, Celsius→Fahrenheit, simple interest) If you’re still only running code in the shell, this is the post that gets you to real programs. 👉 Full guide (free): https://lnkd.in/gxpME4zP What was the first “complete” program you ever wrote? Drop it in the comments. #Python #LearnPython #Programming #Coding #Beginner #PythonProgramming #CodingForBeginners #TechEducation #SoftwareDevelopment #PythonTips #LearnToCode #ProgrammingTips
To view or add a comment, sign in
-
More from this author
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