🧠 What is a Descriptor in Python ? A descriptor is any object that defines one or more of these methods: __get__() → Access attribute __set__() → Set attribute __delete__() → Delete attribute 👉 In simple terms: Descriptors control how attributes behave in a class Why It Matters? Whenever you use: @property 👉 You’re already using descriptors under the hood. Yes — even Django models rely heavily on descriptors. Example: class Descriptor: def __get__(self, instance, owner): print("Getting value") return instance._value def __set__(self, instance, value): print("Setting value") instance._value = value class MyClass: attr = Descriptor() obj = MyClass() obj.attr = 10 # calls __set__ print(obj.attr) # calls __get__ What’s Happening Internally? When you do: obj.attr Python does NOT directly fetch the value. 👉 It checks: Does attr have __get__? If yes → call descriptor logic Real-World Use Cases Descriptors are used in: ✅ @property (getter/setter logic) ✅ Django ORM fields (models.CharField) ✅ Data validation frameworks ✅ Lazy loading attributes ✅ Caching values Example (Validation): class PositiveNumber: def __set__(self, instance, value): if value < 0: raise ValueError("Must be positive") instance.__dict__['value'] = value def __get__(self, instance, owner): return instance.__dict__.get('value', 0) class Product: price = PositiveNumber() p = Product() p.price = 100 # ✅ p.price = -10 # ❌ Error 👉 Clean validation without cluttering your class. Have you ever used descriptors directly, or only via @property? #Python #AdvancedPython #OOP #Django #SoftwareEngineering #BackendDevelopment #infosys #citi #SoftwareDevelopment
Understanding Descriptors in Python: Attributes, Methods, and Use Cases
More Relevant Posts
-
💡 Create custom tools with Python & uv This is my favourite uv workflow. I can turn any one-off script or project into a CLI tool I can install into my own system to create commands I can use easily from anywhere on my machine. It all starts with an app project. You want to build a CLI tool, so that’s an app (not a lib). The uv command for that is `uv init --app ...`. But there’s something else. Later, you’ll want to install the project on your own computer, so it needs to be a package. That means you need an extra piece of data in your file `pyproject.toml`. You could add it by hand... Or you can tell uv to add it for you. Initialise the project with this command: `uv init --app --package example-proj`. If you open the file `pyproject.toml`, you will see a section that looks like this: ```toml [project.scripts] example-proj = "example_proj:main" ``` The section `[project.scripts]` of your file `pyproject.toml` sets the entrypoints of your package. They map commands, like `example-proj`, to functions in your code. Right now, if you run `uv run example-proj`, uv will run the function `main` that’s in the file `src/example_proj/__init__.py`. Try it: ```bash $ uv run example-proj Hello from example-proj! ``` To change the name of the command, change what's to the left of the equals `=` sign. To create more commands, add more lines under `[project.scripts]`. You'll need some code to make your CLI a bit more interesting. This could be any script you wrote before, for example. After you have the code you care about, you want to install the tool. As of now, the project only works if you use it through the command `uv run example-proj` from the root of your repository. What you want to do is make the command accessible everywhere on your system. To do that, you’ll install your own project as a uv tool. To install _this_ project, make sure you’re at the root of your project and run ```bash $ uv tool install -e . ``` The period `.` tells uv to install the current project and the option `-e` makes it an editable install. What does that mean? It means that if you update the code, your installed tool picks up the changes immediately. Otherwise, every time you change the code, you’d have to reinstall the tool. Try opening a new terminal and run the command `uv tool list`. You should see the tool `example-proj` in the output: ```bash $ uv tool list ... example-proj v0.1.0 - example-proj ... ``` Now, the command `example-proj` can be ran from anywhere on your system! I use this a lot to create my own utilities. For example, I have a script that automatically syncs a GitHub repository for when I’m live-coding when I’m giving a training. Every minute, the tool synchronises my work with the repo so that every student has near-live access to all of my work on their machines. That’s a uv project that I installed with `uv tool install -e .`. What tools will you use this for?
To view or add a comment, sign in
-
🚀Python Series – Day 26: JSON in Python (Handle API Data Like a Pro!) Yesterday, we learned APIs in Python🌐 Today, let’s learn how Python works with the most common data format used in APIs: JSON What is JSON? JSON stands for JavaScript Object Notation It is a lightweight format used to store and exchange data. 📌 JSON is easy for humans to read and easy for machines to understand. 🔹 Where is JSON Used? ✔️ APIs ✔️ Web applications ✔️ Config files ✔️ Data exchange between systems 💻 Example of JSON Data { "name": "Mustaqeem", "age": 24, "skills": ["Python", "SQL", "Power BI"] } 💻 Convert JSON to Python Dictionary import json data = '{"name":"Ali","age":22}' result = json.loads(data) print(result) print(result["name"]) 🔍 Output: {'name': 'Ali', 'age': 22} Ali 💻 Convert Python Dictionary to JSON import json student = { "name": "Sara", "age": 23 } json_data = json.dumps(student) print(json_data) 🔍 Output: {"name": "Sara", "age": 23} 🎯 Why JSON is Important? ✔️ Used in almost every API ✔️ Easy data exchange format ✔️ Important for Web Development ✔️ Must-know for Data Science projects ⚠️ Pro Tip 👉 Learn dictionary concepts well, because JSON looks similar to Python dictionaries. 🔥 One-Line Summary 👉 JSON = Standard format to store and exchange data 📌 Tomorrow: SQL with Python (Connect Python with Databases!) Follow me to master Python step-by-step 🚀 #Python #JSON #API #WebDevelopment #DataScience #Coding #Programming #LearnPython #MustaqeemSiddiqui
To view or add a comment, sign in
-
-
Every time you write obj.attribute in Python, something runs that most developers have never heard of. Day 05 of 30 -- Descriptors and Properties Advanced Python + Real Projects Series When Django marks a field dirty on assignment, when SQLAlchemy tracks changes for save(), when Pydantic validates on every write -- they all use the same mechanism. The descriptor protocol. A descriptor is any object defining get, set, or delete. When it sits as a class attribute, Python routes all attribute access through it -- before the instance dict is even touched. Today's Topic covers: Why descriptors exist and what problem @property alone cannot solve The full descriptor protocol -- get, set, delete, set_name Data vs non-data descriptors and why the difference controls lookup priority The 3-level attribute lookup chain Python follows on every access Annotated syntax -- from @property to a fully reusable Validated field Real e-commerce scenario -- auto type check, range validation, and audit logging on every field write across 30 model classes with 3 lines of code How Django, SQLAlchemy, Pydantic, and dataclasses all use this internally 4 mistakes including the infinite recursion trap that kills production apps Key insight: When you write user.email in Django, that single line triggers a descriptor that queues the change for save(). No magic. Just the descriptor protocol. #Python #PythonProgramming #Django #SQLAlchemy #SoftwareEngineering #BackendDevelopment #100DaysOfCode #LearnPython #PythonDeveloper #TechContent #DataEngineering #BuildInPublic #TechIndia #CleanCode #LinkedInCreator #PythonTutorial
To view or add a comment, sign in
-
🔥 Mastering JSON Parsing in Python! 🐍 Ever wondered how to work with JSON in Python? JSON (JavaScript Object Notation) is a popular format for data exchange due to its simplicity and readability. For developers, understanding JSON parsing is essential as it allows you to interact with APIs, handle configuration files, and exchange data between different systems effortlessly. Here are the steps to parse JSON in Python: 1️⃣ Load the JSON data using the `json.loads()` function. 2️⃣ Access the values using keys just like a Python dictionary. 3️⃣ Iterate through JSON arrays to extract multiple values. 👉 Pro Tip: Use `json.dumps()` to convert Python objects back to JSON. ❌ Common Mistake: Forgetting to handle exceptions when parsing JSON can lead to runtime errors. 🚀 Ready to level up your Python skills? Try parsing JSON with this code snippet: ``` import json # Sample JSON data json_data = '{"name": "John", "age": 30, "city": "New York"}' # Parse JSON data = json.loads(json_data) # Access values name = data['name'] age = data['age'] city = data['city'] print(name, age, city) ``` 🤔 What's your favorite way to work with JSON data in Python? 🌐 View my full portfolio and more dev resources at tharindunipun.lk #JSON #Python #APIs #DataExchange #CodingTips #JSONParsing #Programming #DeveloperCommunity #TechSkills
To view or add a comment, sign in
-
-
🔥 **Playwright Python – One Page Cheat Sheet (Save this 📌)** Everything you need in ONE place 👇 --- 🌐 **Browser & Page** `p.chromium.launch()` | `browser.new_page()` | `page.goto("url")` | `browser.close()` --- 🔍 **Locators** `page.locator()` | `page.get_by_text()` | `page.get_by_role()` | `page.get_by_placeholder()` | `page.get_by_label()` --- 🖱️ **Actions** `page.click()` | `page.dblclick()` | `page.fill()` | `page.type()` | `page.press()` | `page.check()` | `page.uncheck()` | `page.select_option()` --- ⏳ **Waits** `page.wait_for_selector()` | `page.wait_for_load_state()` | ❌ avoid `wait_for_timeout()` --- 🔄 **Navigation** `page.go_back()` | `page.go_forward()` | `page.reload()` --- 🪟 **Tabs / Windows** `page.expect_popup()` | `context.new_page()` --- 🧩 **Frames** `page.frame()` | `page.frame_locator()` --- 🚨 **Alerts / Dialogs** `page.on("dialog", handler)` | `dialog.accept()` | `dialog.dismiss()` --- 📸 **Screenshot** `page.screenshot(path="file.png")` --- 📄 **File Upload / Download** `page.set_input_files()` | `page.expect_download()` | `download.save_as()` --- 🌍 **API Testing** `page.request.get()` | `page.request.post()` | `response.json()` | `response.status` --- 🔌 **Network** `page.route()` | `route.continue_()` | `route.abort()` --- 🧪 **Assertions** `expect(locator).to_have_text()` | `expect(locator).to_be_visible()` | `expect(page).to_have_url()` --- ⌨️ **Keyboard / Mouse** `page.keyboard.press()` | `page.mouse.click()` --- 📜 **JS Execution** `page.evaluate()` --- 💡 **Why Playwright?** ✔ Auto-wait | ✔ Fast | ✔ Less flaky | ✔ API + UI in one --- 🚀 If you're in Automation Testing in 2026… Playwright is a must-have skill. 💬 Comment “Playwright” if you want PDF version #Playwright #Python #AutomationTesting #SDET #SoftwareTesting #QA #TestAutomation
To view or add a comment, sign in
-
My Python loop processed 5 reports in 2.5 seconds. After adding one decorator: 0.54 seconds. I changed zero call sites. Here's how it works. A function that's slow because it does real work — database queries, aggregations — gets decorated with @app.direct_task. That's it. The caller doesn't change. Exception handling doesn't change. The return type doesn't change. In development: set one environment variable and the decorator is invisible - tests pass, the function runs inline as it always did. In production: start a worker. The same call now routes to a distributed runner. The caller still blocks and gets the value back directly. No .result. No futures. No refactoring. For parallelism without touching the call site at all: add parallel_func to the decorator with a small helper that describes how to split the input. Pynenc dispatches one task per chunk, collects results, and returns the same type the caller expected. Full write-up + runnable demo (no Docker, no Redis, runs in ~30 seconds): https://lnkd.in/eySD7h_H What's the slowest loop in your codebase right now? #python #backend #distributedsystems #opensource
To view or add a comment, sign in
-
I used to write this in Python: class User: ····def get_age(self): return self.__age ····def set_age(self, value): self.__age = value Java style. Getters. Setters. Looked clean to me. Python has a better way. ━━━━━━━━━━━━━━━━━━━━━━ In Java and C++, getters and setters are the standard way to protect your data. I carried that habit into Python. Turns out Python doesn't need them. ━━━━━━━━━━━━━━━━━━━━━━ Without @property: user.set_age(25) print(user.get_age()) With @property: user.age = 25 print(user.age) Same protection. Zero extra method calls. Reads like a normal variable. ━━━━━━━━━━━━━━━━━━━━━━ But here's the part that actually matters. @property lets you add validation invisibly: @age.setter ····def age(self, value): ········if value < 0: ············raise ValueError("Age cannot be negative") ········self.__age = value Now user.age = -5 raises an error automatically. The person using your class never knows validation is happening. That's what encapsulation actually looks like in Python. ━━━━━━━━━━━━━━━━━━━━━━ Why does this matter for Data Science? When you build a custom data pipeline class or a model wrapper — @property keeps your data clean without exposing the internals. Not just clean code. Safe data. ━━━━━━━━━━━━━━━━━━━━━━ Senior developers — do you still use getters/setters in Python or has @property completely replaced them in your workflow? #Python #OOP #DataScience #100DaysOfCode #SoftwareEngineering
To view or add a comment, sign in
-
-
Day - 28 I used to validate APIs by clicking through Postman one by one. Now I run 100+ tests in seconds with Python. Here's the exact framework I use in production python from dataclasses import dataclass import requests @dataclass class APITest: name: str method: str endpoint: str payload: dict | None expected_status: int expected_fields: list[str] def run_api_tests(base_url: str, tests: list[APITest]): for test in tests: r = requests.request( test.method, f"{base_url}{test.endpoint}", json=test.payload, headers={"Authorization": "Bearer YOUR_TOKEN"} ) body = r.json() if r.content else {} status_ok = r.status_code == test.expected_status fields_ok = all(f in body for f in test.expected_fields) print(f"{test.name}: {'✅' if status_ok and fields_ok else '❌'} | {r.elapsed.microseconds // 1000}ms") # Example test cases tests = [ APITest("Create User", "POST", "/api/users", {"name": "Test User", "email": "test@example.com"}, 201, ["id", "name", "email", "created_at"]), APITest("Get User", "GET", "/api/users/1", None, 200, ["id", "name", "email"]), APITest("Update User", "PUT", "/api/users/1", {"name": "Updated Name"}, 200, ["id", "name", "updated_at"]), ] run_api_tests("https://api.yourapp.com", tests) What this gives you: → 100 tests run in seconds → Status code + field validation in one pass → Response time tracked automatically → Plug in AI to explain every failure instantly No more manual clicking. No more missed fields. No more guessing why it failed. Postman is great for exploring. Python is built for scale. Save this and adapt it to your own API. #Python #APITesting #QAAutomation #SDET #TestAutomation #SoftwareTesting #RestAPI #DevOps #Automation #AI
To view or add a comment, sign in
-
📦 Variables in Python #Day27 If you’re starting with Python, understanding variables is your first big step toward writing real programs 💡 🔹 What is a Variable? A variable is like a container 📦 that stores data which can be used later in your program. 👉 Think of it as a label attached to a value 🔸 How to Create a Variable in Python Python makes it super easy — no need to declare the type! 👉 Example: name = "Ishu" age = 20 price = 99.99 Here: name stores a string 🧑 age stores an integer 🔢 price stores a float 💰 🔸 Rules for Naming Variables 📏 ✔ Must start with a letter (a-z, A-Z) or underscore _ ✔ Cannot start with a number ❌ ✔ Cannot use keywords like if, for, while ✔ Case-sensitive (Name ≠ name) 👉 Valid Examples: user_name = "Ishu" _age = 20 totalPrice = 500 👉 Invalid Examples: 2name = "Error" # Starts with number ❌ for = 10 # Keyword ❌ 🔸 Types of Variables in Python 🧠 Python automatically detects the data type (Dynamic Typing) ⚡ 📌 Common Types: int ➝ Whole numbers (10, 100) float ➝ Decimal numbers (10.5) str ➝ Text ("Hello") bool ➝ True/False 👉 Example: x = 10 # int y = 3.14 # float name = "Hi" # string is_valid = True # boolean 🔸 Dynamic Nature of Variables 🔄 Python allows you to change the type of a variable anytime! 👉 Example: x = 10 x = "Now I'm a string" 🔸 Multiple Assignments 🔗 You can assign multiple values in one line! 👉 Example: a, b, c = 1, 2, 3 Or assign same value: x = y = z = 100 🔸 Constants in Python 🔒 Python doesn’t have true constants, but we use uppercase naming convention 👉 Example: PI = 3.14159 🎯 Why Variables Matter? Without variables, you can’t: ❌ Store data ❌ Perform calculations ❌ Build logic 👉 They are the building blocks of programming 🏗️ 💡 Pro Tip Use meaningful variable names like total_price instead of tp — your future self will thank you 😄 💬 What’s the best variable name you’ve ever used in your code? Clean or confusing? 😅 #Python #Coding #Programming #LearnPython #DataAnalytics #Developers #Tech #DataAnalysts #DataAnalysis #DataCollection #DataCleaning #DataVisualization #PythonProgramming #PowerBI #Excel #MicrosoftExcel #MicrosoftPowerBI #SQL #CodeWithHarry
To view or add a comment, sign in
-
Python optimization is about making your code run faster, use less memory, or scale better. Here are the most practical techniques, explained clearly: --- ## 1. Use Built-in Functions and Libraries Python’s built-in functions are written in optimized C code, so they are much faster than manual implementations. **Example:** ```python # Slow total = 0 for i in range(1000): total += i # Faster total = sum(range(1000)) ``` --- ## 2. Choose the Right Data Structures Different structures have different performance characteristics. * `list` → fast for iteration * `set` → fast membership checks (`in`) * `dict` → fast key-value lookup **Example:** ```python # Slow (list lookup) if x in my_list: # Faster (set lookup) if x in my_set: ``` --- ## 3. Avoid Unnecessary Loops Use list comprehensions or generator expressions instead of manual loops. ```python # Slow squares = [] for x in range(10): squares.append(x*x) # Faster squares = [x*x for x in range(10)] ``` --- ## 4. Use Generators for Large Data Generators don’t store everything in memory. ```python # Uses more memory nums = [x*x for x in range(1000000)] # Memory efficient nums = (x*x for x in range(1000000)) ``` --- ## 5. Optimize Loops * Avoid repeated calculations inside loops * Store values in local variables ```python # Slow for i in range(len(data)): process(data[i]) # Faster for item in data: process(item) ``` --- ## 6. Use `join()` Instead of String Concatenation Strings are immutable, so repeated `+` is slow. ```python # Slow result = "" for word in words: result += word # Faster result = "".join(words) ``` --- ## 7. Use Caching (Memoization) Store results of expensive function calls. ```python from functools import lru_cache @lru_cache(maxsize=None) def fib(n): if n < 2: return n return fib(n-1) + fib(n-2) ``` --- ## 8. Profile Your Code First Before optimizing, find the bottleneck. ```python import cProfile cProfile.run("my_function()") ``` --- ## 9. Use Efficient Libraries Libraries like: * `NumPy` (for numerical computations) * `Pandas` (for data analysis) They are faster than pure Python loops. --- ## 10. Avoid Global Variables Local variables are faster to access. --- ## 11. Use Multiprocessing for CPU-bound Tasks Python has a Global Interpreter Lock (GIL), so use multiprocessing for heavy computations. ```python from multiprocessing import Pool ``` --- ## 12. Use Just-In-Time Compilation Libraries like **Numba** can speed up numerical code. --- ## 13. Reduce Function Calls in Hot Paths Function calls have overhead; inline simple logic if needed. --- ## 14. Use Proper Algorithm Design The biggest optimization comes from choosing the right algorithm. * O(n²) → slow * O(n log n) → better * O(n) → optimal --- ## Key Tip **Don’t optimize blindly.** First make your code correct, then measure, then optimize.
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