Just shipped my first ever CLI tool — and published it to PyPI. pip install mlx-tracker Here's the full story of what I built, what I learned, and why I built it 👇 --- What is mlx? mlx is a local ML experiment tracker that lives entirely in your terminal. No cloud. No server. No account. Just install and track. Every time you train a model you can now do this: mlx run start --name "catboost-v1" python train.py mlx run stop mlx compare catboost-v1 catboost-v2 And instantly see which model won — and exactly why. --- Tech Stack - Python — core language - Typer — turns Python functions into CLI commands - Rich — beautiful terminal output (tables, panels, colors) - SQLModel — SQLite database with Python classes (zero setup) - TOML — config file management - pytest — 38 automated tests, 95% coverage - GitHub Actions — CI on every push + auto publish to PyPI - Hatchling — modern Python packaging --- What I actually built The architecture has 3 clean layers: - Commands layer — what the user types (Typer CLI) - Core layer — business logic (Managers for Run, Metric, Param) - Storage layer — SQLite database + filesystem Commands never touch the database directly. Core handles everything in between. Clean separation of concerns. --- Commands shipped: - mlx init — set up any ML project - mlx run start/stop — track training sessions - mlx log metric/param/note — log everything - mlx ls — see all runs in a table - mlx status — inspect any run in detail - mlx compare — side by side diff of two runs - mlx export — save to CSV or JSON --- Things I learned building this 1. How Python packages actually work — pyproject.toml, entry points, editable installs 2. The 3-layer architecture pattern — separating CLI, logic, and storage makes code actually maintainable 3. pytest from scratch — fixtures, conftest.py, CliRunner, coverage reports 4. How PyPI publishing works end to end — build, twine, API tokens, GitHub Actions 5. Writing a CLI that feels good to use — silent logging, clear error messages, helpful next steps --- Tested with real models I tracked real CatBoost training runs during development. Two models, different hyperparameters, side by side comparison in one command. This is what MLflow and Weights & Biases charge money for. I built it locally in pure Python. --- - I recorded a full demo video showing mlx working live — tracking a CatBoost fraud detection model from init to compare. --- This is my first CLI based project and first open source package on PyPI. If you work with ML models and hate losing track of your experiments — give it a try: pip install mlx-tracker Feedback, stars, and contributions welcome GitHub:https://lnkd.in/gjEh4aUv PyPI: https://lnkd.in/gr2M7tZn #Python #MachineLearning #MLOps #OpenSource #CLI #PyPI #buildinpublic #100DaysOfCode
More Relevant Posts
-
Hey guys!! I think this is pretty cool and interesting. Over the past few months, I've been experimenting on how can I make FastAPI faster, as it slowed down at scale. I tried Rust, but there were issues with the FFI layer(PyO3) from time to time, and since I have been experimenting with Zig lately, I just ended up rewriting FastAPI's HTTP core in Zig. It's 22x faster. FastAPI is the best Python API framework to write. But every request flows through six layers of Python - uvicorn, ASGI, Starlette, json.loads, your handler, json.dumps, response. All GIL-serialized. TurboAPI replaces everything below your handler with Zig. Same decorators. Same @app.get(). Same Depends(). Same Pydantic-style models. Your code doesn't change - just swap the import. What Zig does under the hood: At startup, TurboAPI classifies each route and assigns the lightest dispatch path: → simple_sync_noargs - response cached after first call, subsequent requests skip Python entirely (150k req/s) → simple_sync - Zig assembles args via vectorcall, no kwargs dict (143k req/s) → model_sync - Zig parses and validates JSON before touching Python, single-parse pipeline (124k req/s) → static_route - response pre-rendered at startup, single writeAll (149k req/s) The numbers (Python 3.14 free-threading, wrk 4t/100c/10s, M3 Pro): TurboAPI → 150,000 req/s (GET) vs FastAPI → 6,847 TurboAPI → 124,000 req/s (POST) vs FastAPI → 8,200 Avg latency: 0.15ms vs 14.6ms CORS overhead: 0% (Zig-native) vs Python middleware JSON parsing: Zig (0 Python calls) vs json.loads Validation: Zig-native (dhi, still in alpha - https://lnkd.in/g4kmQXQQ) vs Pydantic 275 tests passing. FastAPI parity on routing, path params, query params, security (OAuth2, HTTPBearer, APIKey), middleware (CORS, GZip), Depends(), background tasks, response types. What's different from just using uvloop/orjson/etc: Those optimize within Python. TurboAPI moves the entire HTTP layer out of Python. The Zig server handles TCP, HTTP parsing, routing, JSON, validation, and CORS - Python only runs your business logic. Key optimizations in this release: → Zero-alloc response pipeline (stack buffers, no heap allocs per request) → Zig-native CORS (headers pre-rendered once, 0% overhead vs 24% with Python middleware) → Response caching for noargs handlers (Python called once, cached forever) → Zero-alloc route params (stack array replaces HashMap) → Fuzz-tested HTTP parser, router, and JSON validator → 10 security bugs fixed from community audit Stack: Zig 0.15 HTTP core (24-thread pool, keep-alive, radix-trie router), dhi for Pydantic-compatible validation (Zig-native, https://lnkd.in/g4kmQXQQ), Python 3.14 free-threading (no GIL). Still alpha(very experimental). WebSocket and HTTP/2 are next. Check it out over at: https://lnkd.in/gTnk_wmp Built with devswarm: https://lnkd.in/gbrjp4MG
To view or add a comment, sign in
-
-
🚀 Write Cleaner, Faster, Scalable Python — For System Design & Product Roles Syntax isn’t enough. These concepts separate good devs from great ones 👇 --- 🔹 References, Not Values a=[1,2]; b=a; b.append(3) print(a) # [1,2,3] 🌍 Shared object (like a Google Doc) → impacts bugs & performance --- 🔹 "==" vs "is" a=[1]; b=[1] a==b # True a is b # False 👉 Value vs identity ✅ Use "is None" --- 🔹 "__dict__" (Object Storage) u.__dict__ # {'name': 'Abhi', 'age': 25} 🌍 Backbone of Django models / serializers --- 🔹 "__slots__" (Memory Optimization) class U: __slots__=['name'] ⚡ Saves RAM in large-scale object creation --- 🔹 "setattr" (Dynamic Attributes) for k,v in data.items(): setattr(u,k,v) 🌍 Map API JSON → objects --- 🔹 "getattr" (Dynamic Execution) getattr(obj,"add")(2,3) 🌍 Replace bulky if-else (plugins, routers) --- 🔹 Decorators (Reusable Logic) @auth def api(): ... 🌍 Used in Django, Flask (auth, logging) --- 🔹 Decorator Order @A @B # A(B(func)) --- 🔹 "__new__" vs "__init__" Object creation vs initialization 🌍 Used in Singletons (DB connections) --- 🔹 O(1) Lookup (dict/set) "x" in set_data # fast 🌍 Caching, dedup, auth --- 🔹 """.join()" > "+=" "".join(list_data) ⚡ Avoids repeated allocations --- 🔹 List Comprehension [x*x for x in range(5)] ⚡ Cleaner + faster transforms --- 🔹 Generators yield i 🌍 Handle large data without memory crash --- 🔹 "islice" (Lazy slicing) list(islice(gen(),5)) --- 🔹 Threading vs AsyncIO - Threading → I/O tasks - AsyncIO → high concurrency (FastAPI) --- 🔹 EAFP (Pythonic) try: val=d["k"] except KeyError: val=None ⚡ Faster than pre-checks --- 💡 Powers: Django, FastAPI, AI pipelines, scalable systems 🎯 Grow to Architect Level: ✔ Clean code ✔ Scalable design ✔ Strong fundamentals --- #Python #Backend #SystemDesign #SoftwareEngineer #AdvancedPython #TechCareers
To view or add a comment, sign in
-
-
Another week, another Python decorator -- Observability, alerting, and auditability in less of 100 lines of generated code. Last week I walked through a decorator that automatically manages authentication tokens for REST service calls — a simple but powerful example of eliminating boilerplate from your pipeline code. A few of you asked for more context around the prompt I used and the thinking behind it. Fair point — let's do that properly this time. I've been exploring decorators through the lens of Aspect Oriented Programming (AOP). The core idea is straightforward: decorators let you define an annotation that wraps any function with pre- and post-invocation behavior, without touching the function itself. Cross-cutting concerns — authentication, logging, error handling — get defined once and applied everywhere. Last week's token management example was a natural fit because it's something we do constantly in data engineering. This week we're tackling something more substantial. The @watchdog decorator drops onto any function and delivers observability, alerting, and auditability out of the box. Before invocation we start a timer, invoke the target function, capture the runtime, write an audit record to a Delta table, and wrap the entire thing in a try/except that fires an alert on failure. One annotation — three cross-cutting concerns handled. I am using Claude/Sonnet this week and this is the prompt I am going to run: Dear LLM, please write a basic python decorator that can be applied to any function. Our goal is observability, alerting, and auditability. I want this to be as generic as possible without any parameters going into the decorator. We will be using this in Databricks. I want this to capture run time of the attributed function. I want this to log pertinent information including the run time and what user ran it by appending records to a table, monitoring.audits.watchdog. And I want there to be some error handling with a try/except so that on exception we can print or log information about the failure and send an alert. Name this decorator @watchdog. We get back exactly what we needed — zero parameters, no changes to existing pipeline code, and a clean audit trail written directly to monitoring.audits.watchdog in Databricks. All we have to do is add @watchog to any function. I will save my output and include it as an attachment. One thing still to define is how alerts actually get routed. The send_alert stub is intentionally left open since that will vary by team and stack — Slack, Teams, PagerDuty, and Delta audit tables are all fair game. That feels like a natural next installment. I call this a win. Hopefully everyone can see how powerful these decorators are and how easy it is for an AI assistant to write functional bits of code. Usage Example (trivial but still including it): @watchdog def ingest_raw_sales(spark, source_path): # your pipeline logic here pass Code Attached.
To view or add a comment, sign in
-
Python Learning Plan |-- Week 1: Introduction to Python | |-- Python Basics | | |-- What is Python? | | |-- Installing Python | | |-- Introduction to IDEs (Jupyter, VS Code) | |-- Setting up Python Environment | | |-- Anaconda Setup | | |-- Virtual Environments | | |-- Basic Syntax and Data Types | |-- First Python Program | | |-- Writing and Running Python Scripts | | |-- Basic Input/Output | | |-- Simple Calculations | |-- Week 2: Core Python Concepts | |-- Control Structures | | |-- Conditional Statements (if, elif, else) | | |-- Loops (for, while) | | |-- Comprehensions | |-- Functions | | |-- Defining Functions | | |-- Function Arguments and Return Values | | |-- Lambda Functions | |-- Modules and Packages | | |-- Importing Modules | | |-- Standard Library Overview | | |-- Creating and Using Packages | |-- Week 3: Advanced Python Concepts | |-- Data Structures | | |-- Lists, Tuples, and Sets | | |-- Dictionaries | | |-- Collections Module | |-- File Handling | | |-- Reading and Writing Files | | |-- Working with CSV and JSON | | |-- Context Managers | |-- Error Handling | | |-- Exceptions | | |-- Try, Except, Finally | | |-- Custom Exceptions | |-- Week 4: Object-Oriented Programming | |-- OOP Basics | | |-- Classes and Objects | | |-- Attributes and Methods | | |-- Inheritance | |-- Advanced OOP | | |-- Polymorphism | | |-- Encapsulation | | |-- Magic Methods and Operator Overloading | |-- Design Patterns | | |-- Singleton | | |-- Factory | | |-- Observer | |-- Week 5: Python for Data Analysis | |-- NumPy | | |-- Arrays and Vectorization | | |-- Indexing and Slicing | | |-- Mathematical Operations | |-- Pandas | | |-- DataFrames and Series | | |-- Data Cleaning and Manipulation | | |-- Merging and Joining Data | |-- Matplotlib and Seaborn | | |-- Basic Plotting | | |-- Advanced Visualizations | | |-- Customizing Plots | |-- Week 6-8: Specialized Python Libraries | |-- Web Development | | |-- Flask Basics | | |-- Django Basics | |-- Data Science and Machine Learning | | |-- Scikit-Learn | | |-- TensorFlow and Keras | |-- Automation and Scripting | | |-- Automating Tasks with Python | | |-- Web Scraping with BeautifulSoup and Scrapy | |-- APIs and RESTful Services | | |-- Working with REST APIs | | |-- Building APIs with Flask/Django | |-- Week 9-11: Real-world Applications and Projects | |-- Capstone Project | | |-- Project Planning | | |-- Data Collection and Preparation | | |-- Building and Optimizing Models | | |-- Creating and Publishing Reports Here you can find essential Python Interview Resources👇 https://lnkd.in/d5F8krMt Like this post for more resources like this 👍♥️ Follow Data Analytics for more resources Hope it helps :)
To view or add a comment, sign in
-
-
Python isn’t just a language — it’s an entire ecosystem. From crunching data with Pandas and NumPy, to building intelligent systems with TensorFlow and PyTorch, to creating powerful AI workflows with tools like LangChain and Hugging Face — Python truly does it all. Whether you’re diving into data science, machine learning, visualization, or even web scraping, there’s a library ready to help you move faster and build smarter. The real superpower? It lets beginners start quickly and gives experts the depth to build anything. What’s your go-to Python library right now?
Python Learning Plan |-- Week 1: Introduction to Python | |-- Python Basics | | |-- What is Python? | | |-- Installing Python | | |-- Introduction to IDEs (Jupyter, VS Code) | |-- Setting up Python Environment | | |-- Anaconda Setup | | |-- Virtual Environments | | |-- Basic Syntax and Data Types | |-- First Python Program | | |-- Writing and Running Python Scripts | | |-- Basic Input/Output | | |-- Simple Calculations | |-- Week 2: Core Python Concepts | |-- Control Structures | | |-- Conditional Statements (if, elif, else) | | |-- Loops (for, while) | | |-- Comprehensions | |-- Functions | | |-- Defining Functions | | |-- Function Arguments and Return Values | | |-- Lambda Functions | |-- Modules and Packages | | |-- Importing Modules | | |-- Standard Library Overview | | |-- Creating and Using Packages | |-- Week 3: Advanced Python Concepts | |-- Data Structures | | |-- Lists, Tuples, and Sets | | |-- Dictionaries | | |-- Collections Module | |-- File Handling | | |-- Reading and Writing Files | | |-- Working with CSV and JSON | | |-- Context Managers | |-- Error Handling | | |-- Exceptions | | |-- Try, Except, Finally | | |-- Custom Exceptions | |-- Week 4: Object-Oriented Programming | |-- OOP Basics | | |-- Classes and Objects | | |-- Attributes and Methods | | |-- Inheritance | |-- Advanced OOP | | |-- Polymorphism | | |-- Encapsulation | | |-- Magic Methods and Operator Overloading | |-- Design Patterns | | |-- Singleton | | |-- Factory | | |-- Observer | |-- Week 5: Python for Data Analysis | |-- NumPy | | |-- Arrays and Vectorization | | |-- Indexing and Slicing | | |-- Mathematical Operations | |-- Pandas | | |-- DataFrames and Series | | |-- Data Cleaning and Manipulation | | |-- Merging and Joining Data | |-- Matplotlib and Seaborn | | |-- Basic Plotting | | |-- Advanced Visualizations | | |-- Customizing Plots | |-- Week 6-8: Specialized Python Libraries | |-- Web Development | | |-- Flask Basics | | |-- Django Basics | |-- Data Science and Machine Learning | | |-- Scikit-Learn | | |-- TensorFlow and Keras | |-- Automation and Scripting | | |-- Automating Tasks with Python | | |-- Web Scraping with BeautifulSoup and Scrapy | |-- APIs and RESTful Services | | |-- Working with REST APIs | | |-- Building APIs with Flask/Django | |-- Week 9-11: Real-world Applications and Projects | |-- Capstone Project | | |-- Project Planning | | |-- Data Collection and Preparation | | |-- Building and Optimizing Models | | |-- Creating and Publishing Reports Here you can find essential Python Interview Resources👇 https://lnkd.in/d5F8krMt Like this post for more resources like this 👍♥️ Follow Data Analytics for more resources Hope it helps :)
To view or add a comment, sign in
-
-
🚀 Python Roadmap for Data Analytics & AI A simple and powerful guide covering key areas like data analysis, visualization, machine learning, NLP, and more. Start small, stay consistent, and build projects along the way. #Python #DataAnalytics #AI #MachineLearning #DataScience
Python Learning Plan |-- Week 1: Introduction to Python | |-- Python Basics | | |-- What is Python? | | |-- Installing Python | | |-- Introduction to IDEs (Jupyter, VS Code) | |-- Setting up Python Environment | | |-- Anaconda Setup | | |-- Virtual Environments | | |-- Basic Syntax and Data Types | |-- First Python Program | | |-- Writing and Running Python Scripts | | |-- Basic Input/Output | | |-- Simple Calculations | |-- Week 2: Core Python Concepts | |-- Control Structures | | |-- Conditional Statements (if, elif, else) | | |-- Loops (for, while) | | |-- Comprehensions | |-- Functions | | |-- Defining Functions | | |-- Function Arguments and Return Values | | |-- Lambda Functions | |-- Modules and Packages | | |-- Importing Modules | | |-- Standard Library Overview | | |-- Creating and Using Packages | |-- Week 3: Advanced Python Concepts | |-- Data Structures | | |-- Lists, Tuples, and Sets | | |-- Dictionaries | | |-- Collections Module | |-- File Handling | | |-- Reading and Writing Files | | |-- Working with CSV and JSON | | |-- Context Managers | |-- Error Handling | | |-- Exceptions | | |-- Try, Except, Finally | | |-- Custom Exceptions | |-- Week 4: Object-Oriented Programming | |-- OOP Basics | | |-- Classes and Objects | | |-- Attributes and Methods | | |-- Inheritance | |-- Advanced OOP | | |-- Polymorphism | | |-- Encapsulation | | |-- Magic Methods and Operator Overloading | |-- Design Patterns | | |-- Singleton | | |-- Factory | | |-- Observer | |-- Week 5: Python for Data Analysis | |-- NumPy | | |-- Arrays and Vectorization | | |-- Indexing and Slicing | | |-- Mathematical Operations | |-- Pandas | | |-- DataFrames and Series | | |-- Data Cleaning and Manipulation | | |-- Merging and Joining Data | |-- Matplotlib and Seaborn | | |-- Basic Plotting | | |-- Advanced Visualizations | | |-- Customizing Plots | |-- Week 6-8: Specialized Python Libraries | |-- Web Development | | |-- Flask Basics | | |-- Django Basics | |-- Data Science and Machine Learning | | |-- Scikit-Learn | | |-- TensorFlow and Keras | |-- Automation and Scripting | | |-- Automating Tasks with Python | | |-- Web Scraping with BeautifulSoup and Scrapy | |-- APIs and RESTful Services | | |-- Working with REST APIs | | |-- Building APIs with Flask/Django | |-- Week 9-11: Real-world Applications and Projects | |-- Capstone Project | | |-- Project Planning | | |-- Data Collection and Preparation | | |-- Building and Optimizing Models | | |-- Creating and Publishing Reports Here you can find essential Python Interview Resources👇 https://lnkd.in/d5F8krMt Like this post for more resources like this 👍♥️ Follow Data Analytics for more resources Hope it helps :)
To view or add a comment, sign in
-
-
Python Learning Plan |-- Week 1: Introduction to Python | |-- Python Basics | | |-- What is Python? | | |-- Installing Python | | |-- Introduction to IDEs (Jupyter, VS Code) | |-- Setting up Python Environment | | |-- Anaconda Setup | | |-- Virtual Environments | | |-- Basic Syntax and Data Types | |-- First Python Program | | |-- Writing and Running Python Scripts | | |-- Basic Input/Output | | |-- Simple Calculations | |-- Week 2: Core Python Concepts | |-- Control Structures | | |-- Conditional Statements (if, elif, else) | | |-- Loops (for, while) | | |-- Comprehensions | |-- Functions | | |-- Defining Functions | | |-- Function Arguments and Return Values | | |-- Lambda Functions | |-- Modules and Packages | | |-- Importing Modules | | |-- Standard Library Overview | | |-- Creating and Using Packages | |-- Week 3: Advanced Python Concepts | |-- Data Structures | | |-- Lists, Tuples, and Sets | | |-- Dictionaries | | |-- Collections Module | |-- File Handling | | |-- Reading and Writing Files | | |-- Working with CSV and JSON | | |-- Context Managers | |-- Error Handling | | |-- Exceptions | | |-- Try, Except, Finally | | |-- Custom Exceptions | |-- Week 4: Object-Oriented Programming | |-- OOP Basics | | |-- Classes and Objects | | |-- Attributes and Methods | | |-- Inheritance | |-- Advanced OOP | | |-- Polymorphism | | |-- Encapsulation | | |-- Magic Methods and Operator Overloading | |-- Design Patterns | | |-- Singleton | | |-- Factory | | |-- Observer | |-- Week 5: Python for Data Analysis | |-- NumPy | | |-- Arrays and Vectorization | | |-- Indexing and Slicing | | |-- Mathematical Operations | |-- Pandas | | |-- DataFrames and Series | | |-- Data Cleaning and Manipulation | | |-- Merging and Joining Data | |-- Matplotlib and Seaborn | | |-- Basic Plotting | | |-- Advanced Visualizations | | |-- Customizing Plots | |-- Week 6-8: Specialized Python Libraries | |-- Web Development | | |-- Flask Basics | | |-- Django Basics | |-- Data Science and Machine Learning | | |-- Scikit-Learn | | |-- TensorFlow and Keras | |-- Automation and Scripting | | |-- Automating Tasks with Python | | |-- Web Scraping with BeautifulSoup and Scrapy | |-- APIs and RESTful Services | | |-- Working with REST APIs | | |-- Building APIs with Flask/Django | |-- Week 9-11: Real-world Applications and Projects | |-- Capstone Project | | |-- Project Planning | | |-- Data Collection and Preparation | | |-- Building and Optimizing Models | | |-- Creating and Publishing Reports
To view or add a comment, sign in
-
-
Python Learning Plan |-- Week 1: Introduction to Python | |-- Python Basics | | |-- What is Python? | | |-- Installing Python | | |-- Introduction to IDEs (Jupyter, VS Code) | |-- Setting up Python Environment | | |-- Anaconda Setup | | |-- Virtual Environments | | |-- Basic Syntax and Data Types | |-- First Python Program | | |-- Writing and Running Python Scripts | | |-- Basic Input/Output | | |-- Simple Calculations | |-- Week 2: Core Python Concepts | |-- Control Structures | | |-- Conditional Statements (if, elif, else) | | |-- Loops (for, while) | | |-- Comprehensions | |-- Functions | | |-- Defining Functions | | |-- Function Arguments and Return Values | | |-- Lambda Functions | |-- Modules and Packages | | |-- Importing Modules | | |-- Standard Library Overview | | |-- Creating and Using Packages | |-- Week 3: Advanced Python Concepts | |-- Data Structures | | |-- Lists, Tuples, and Sets | | |-- Dictionaries | | |-- Collections Module | |-- File Handling | | |-- Reading and Writing Files | | |-- Working with CSV and JSON | | |-- Context Managers | |-- Error Handling | | |-- Exceptions | | |-- Try, Except, Finally | | |-- Custom Exceptions | |-- Week 4: Object-Oriented Programming | |-- OOP Basics | | |-- Classes and Objects | | |-- Attributes and Methods | | |-- Inheritance | |-- Advanced OOP | | |-- Polymorphism | | |-- Encapsulation | | |-- Magic Methods and Operator Overloading | |-- Design Patterns | | |-- Singleton | | |-- Factory | | |-- Observer | |-- Week 5: Python for Data Analysis | |-- NumPy | | |-- Arrays and Vectorization | | |-- Indexing and Slicing | | |-- Mathematical Operations | |-- Pandas | | |-- DataFrames and Series | | |-- Data Cleaning and Manipulation | | |-- Merging and Joining Data | |-- Matplotlib and Seaborn | | |-- Basic Plotting | | |-- Advanced Visualizations | | |-- Customizing Plots | |-- Week 6-8: Specialized Python Libraries | |-- Web Development | | |-- Flask Basics | | |-- Django Basics | |-- Data Science and Machine Learning | | |-- Scikit-Learn | | |-- TensorFlow and Keras | |-- Automation and Scripting | | |-- Automating Tasks with Python | | |-- Web Scraping with BeautifulSoup and Scrapy | |-- APIs and RESTful Services | | |-- Working with REST APIs | | |-- Building APIs with Flask/Django | |-- Week 9-11: Real-world Applications and Projects | |-- Capstone Project | | |-- Project Planning | | |-- Data Collection and Preparation | | |-- Building and Optimizing Models | | |-- Creating and Publishing Reports
To view or add a comment, sign in
-
-
𝗗𝗮𝘆 𝟲𝟰: 𝗛𝗼𝘄 𝗣𝘆𝘁𝗵𝗼𝗻 𝗖𝗹𝗮𝘀𝘀𝗲𝘀 𝗕𝗲𝗰𝗼𝗺𝗲 𝗗𝗷𝗮𝗻𝗴𝗼 𝗠𝗼𝗱𝗲𝗹𝘀 Today I linked two big ideas. Python object oriented programming. And Django models. They are the same thing. A Django model is just a Python class. Here is what I learned about Python classes. A class is a blueprint. An object is a built thing from that blueprint. - class Car: defines the blueprint. - __init__ runs when you build the object. self points to that new object. - Instance attributes like self.brand are unique to each object. - Class attributes like company are shared by all objects. Methods live inside classes. - Instance method: uses self. Works with your object's data. - Class method: uses cls. Decorated with @classmethod. Works with the class itself. - Static method: uses no self or cls. Decorated with @staticmethod. Just a function inside the class. Inheritance lets a child class reuse a parent class. - class Dog(Animal): Dog gets all of Animal's code. - Use super() to run the parent's __init__. Python does not have private. It has conventions. - _name is protected. A hint to other coders. - __name is private. Python changes its name to _ClassName__name. Dunder methods define how your object acts with Python's built-ins. - __str__: for print() and str(). - __len__: for len(). - __eq__: for ==. Abstract Base Classes force subclasses to write specific methods. - from abc import ABC, abstractmethod - @abstractmethod means "you must write this method". Now for Django. A Django model is a Python class that inherits from models.Model. - Each class attribute becomes a database column. - Django reads these attributes and creates the SQL table for you. You do not write SQL. You run two commands. - python manage.py makemigrations - python manage.py migrate The __str__ method in your model controls what you see in the Django admin. Without it you see "Post object (1)". With it you see your post title. OOP is the foundation. Django models are the practical application. A model class maps directly to a database table. Fields map to columns. Your __str__ method controls the display. Understanding Python classes first makes Django models obvious. Source: https://lnkd.in/gChPWWZS
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
nice