Ever had your entire script fail because of a single space? 😅 I was solving a real-world problem: monitoring disk space usage using a Bash script 💻 Simple goal → trigger an alert when usage crosses a threshold 🚨 Everything looked correct. Logic? Fine. Commands? Fine. Still… it failed ❌ The culprit? DISK_USAGE = $(command) That one extra space around "=" sign, broke everything 💥 In Bash, variable assignment is strict: NO spaces allowed. Correct: DISK_USAGE=$(command) ✅ Incorrect: DISK_USAGE = $(command) ❌ That tiny difference cost debugging time ⏳ This is where it gets interesting 👇 As Python developers 🐍, we are used to writing: x = 10 It improves readability. It’s clean. It’s encouraged. But carry that same habit into Bash… and it breaks your code. Why? Because in Bash: Spaces are not cosmetic Spaces are syntax ⚙️ The shell interprets: DISK_USAGE = value as: Command: DISK_USAGE Argument: = Argument: value Which results in an error 😵 Lesson for every developer 🚀 We often switch between languages: Python, Bash, JavaScript, C++ But each language has its own rules. A good habit in one language can become a bug in another. Key takeaways: Be language-aware, not habit-driven 🧠 Understand how your code is interpreted 🔍 Never assume syntax consistency across languages ❗ The smallest characters can cause the biggest failures 🐞 If you are preparing for interviews or working on real systems, these tiny details matter more than you think. Have you ever been stuck because of something this small? Share your experience 👇 #SoftwareEngineering #Python #Bash #DevTips #CodingMistakes #Debugging #LearnToCode #100DaysOfCode #TechCareers #Programming
Bash Scripting Gotcha: Spaces in Variable Assignment
More Relevant Posts
-
I created language development skills (TY/PY/Rust) Lint + Design + Patterns. Extracted from Linter rulesets, Official Google and Microsoft guides. Check them out: https://lnkd.in/dEVqd_Kv Python Example: `npx skills add youssef-tharwat/lang-guidelines --skill python-guidelines -g`
To view or add a comment, sign in
-
My project of the day: NaturalScript - write & maintain executable scripts in natural language I find it off-putting when people generate scripts with LLMs and commit the results to Git repositories. Those scripts are verbose and hard to maintain. It's like committing a binary file without the actual source code. NaturalScript lets you write and maintain executable scripts in natural language. It lets you treat shell/Python/... scripts as generated artifacts that you don't edit directly. Let me know what you think. https://lnkd.in/erEt6ZxH
To view or add a comment, sign in
-
Unpopular opinion: If-statements are killing your Python codebase. And I have the receipts. Every time I wrote code, I made the same mistake: I validate data with nested conditionals. if not isinstance(age, int): raise ValueError if age < 0: raise ValueError if not email or "@" not in email: raise ValueError ...and so on. For every field. In every endpoint. Then I wonder why my code is impossible to maintain. Here's the brutal truth 👇 Manual validation fails at the first error. I fixed it. Submitted again. Hits the next error. Rage quit and annoyed. Pydantic fixes this in one move: → Collects ALL errors at once → Auto-coerces "123" into 123 → Replaces 50 lines of if-statements with 5 type hints → Built-in types for emails, URLs, and secrets → Custom logic via @field_validator when you need it → One-line serialization to dict or JSON class User(BaseModel): name: str age: int email: EmailStr That's a production-grade validator. Not a toy example. A real one. The same pattern powers FastAPI, LangChain, and OpenAI's Python SDK. If you're still hand-rolling validation logic, you're not writing Python. You're writing Java from 2008. --- Disagree? I'll wait in the comments 👀 #Python #Pydantic #BackendDevelopment #CleanCode #SoftwareEngineering
To view or add a comment, sign in
-
-
So I was making a VS Code extension and made a request that apparently isn't supported. Instead of saying "no" the agent spent half an hour writing Python code and dig the guts of the IDE to find how exactly it works to give me what I asked for! I mean, I appreciate the effort but one of my code principals is to "Never fight the tool" (the tool being the VS Code Extension API in this case). Thought it was fun to share but don't worry for me. I'll tighten it up. While you're here, don't forget to set the "Chat: Font Size" to something readable. It's easy to ignore what the agent is doing (and if you're not an engineer it's totally fine) but for an engineer, it's important to understand the tool and what's going on.
To view or add a comment, sign in
-
-
Stop Writing "Mystery Code": The Power of Python Docstrings 🐍 When we build functions, we often focus solely on making the code run. However, well-designed code isn't just about execution; it's about communication. If you've ever returned to a project after a few months only to realize you’ve forgotten how your own functions work, you know the struggle. This is where docstrings become your best friend. A docstring is a specialized string used to describe what a function does, acting as a built-in manual that stays with your code wherever it goes. How to Structure Your Documentation To move beyond basic notes and write professional grade documentation, you should follow a multi-line format. This is particularly useful for complex research or data science functions that handle multiple variables: The One-Line Summary: Always start with a brief, high-level description of the function's purpose immediately following the function definition, wrapped in triple quotation marks """. Defining Arguments (Args): After a blank line, list the function’s arguments. For each one, specify the name, the expected data type in brackets, and a brief description of what it represents. Describing Returns: Finally, include a "Returns" section. This tells the user exactly what the function will output and what data type to expect (e.g., a float, a list, or a dataframe). The Bottom Line Writing documentation might feel like an extra step, but it is the hallmark of a disciplined developer. Whether you are working on academic research or building a commercial app, docstrings ensure your work is scalable, shareable, and most importantly understandable. How do you document your projects? Let’s share best practices in the comments! 👇 #PythonProgramming #CleanCode #DataEngineering #CodingTips #TechCommunity
To view or add a comment, sign in
-
🚀 **I thought I knew Python… until I revisited the fundamentals.** As someone already working in a technical environment, I realized something important: 👉 Strong basics = Strong future in tech So today, I went back and strengthened some **core Python concepts** that actually make code more reliable and professional. 💡 What I learned today: - How to handle errors using `try-except` - Difference between **ValueError** and **IndexError** - Why `finally` always runs (no matter what) - How to create **custom errors using `raise`** - Writing cleaner code using **shorthand if-else** - Using `enumerate()` instead of manual indexing - Setting up **virtual environments (venv)** for real projects - How Python `import` actually works - Exploring modules using `dir()` - Using the **os module** to interact with the system - Understanding **local vs global variables** --- 🔑 Key Takeaways: - Writing code is easy — writing **robust code** is a skill - Error handling is what separates beginners from professionals - Virtual environments are **non-negotiable** in real-world projects - Clean and readable code saves time (yours & others’) --- 🌍 Real-World Relevance: These concepts are not just theory: - Used in **web scraping automation** - Essential for **backend development** - Critical in **production-level systems** --- 📈 I’m actively working on improving my fundamentals to move toward **advanced development and scalable systems**. --- 💬 **Question for you:** What’s one basic concept you revisited recently that changed your understanding? 👉 Let’s grow together — Connect & Follow for more learning updates! --- #Python #WebDevelopment #LearningJourney #Coding #100DaysOfCode #CareerGrowth #Programming #Developers #TechSkills
To view or add a comment, sign in
-
-
I thought error handling was just “avoiding crashes”… I was wrong. Today I practiced handling multiple exceptions in Python — and it completely changed how I look at writing reliable code. What I worked on: Taking user input safely using int(input()) Handling invalid inputs with ValueError Preventing runtime crashes like division by zero (ZeroDivisionError) Structuring multiple except blocks for different failure cases What’s actually happening behind the scenes: Python executes the try block normally If an error occurs → it immediately jumps to the matching except block Each except targets a specific failure scenario The program doesn’t crash — it responds gracefully Why this matters (real understanding): Before this, I wrote code assuming users would behave “correctly.” Now I design code assuming they won’t. That shift changes everything. Real-world relevance: Every backend system, API, or production app deals with unpredictable inputs. Error handling isn’t optional — it’s what makes software robust. What changed for me: I’ve stopped writing “happy path only” code. Now I think in terms of: → What can go wrong? → How should my program respond? Small shift. Big impact. Consistency over intensity. Building step by step. How do you usually approach error handling — after writing logic or while designing it? #Python #ErrorHandling #BackendDevelopment #APIs #Programming #SoftwareEngineering #LearnInPublic #DeveloperJourney #CodingPractice #GenAI
To view or add a comment, sign in
-
-
🐍 **Python support is coming to AI MR Reviewer — this Sunday.** After rolling out Java and JavaScript, the next major milestone is here. This Sunday, Python joins the lineup — bringing the same fast, inline, severity-based PR reviews your team already relies on, now for Python codebases. No setup. No delays. Just actionable feedback the moment you open a PR. **Here's what the Python analyzer covers in v1:** 🔴 **HIGH — Security & Critical Issues** → SQL injection via string formatting or concatenation → Use of `eval()` / `exec()` → Hardcoded secrets — API keys, tokens, passwords → `subprocess` calls with `shell=True` → Insecure deserialization (`pickle` / `yaml.load` without safe loader) → Bare `except:` blocks — silent failure risks → Debug mode left enabled in production frameworks 🟡 **MID — Code Quality & Maintainability** → `print()` statements in production code → Broad exception handling without specificity → Mutable default arguments in functions → Long functions or too many parameters → Missing context managers (`open()` without `with`) → Deprecated libraries or patterns (basic detection) 🔵 **LOW — Clean Code & Hygiene** → `TODO` / `FIXME` / `HACK` comments → Magic numbers without named constants → Non-descriptive variable or function names → Unused imports (basic detection) → Inconsistent naming — PEP8 signal detection **Every rule is built around one principle: low noise, high signal.** Your team only sees what truly matters. ⚡ **Same experience. Extended to Python.** ✅ Inline comments directly on PR diffs ✅ Clear severity levels — HIGH / MID / LOW ✅ Instant feedback within seconds of opening a PR 🚀 Going live this Sunday, InshaAllah. If your team works with Python daily — this is built for you. 👉 Install now: https://lnkd.in/dNaHtm2J 🌐 Learn more: primeoctopus.com #Python #CodeReview #AI #DeveloperTools #StaticAnalysis #DevEx #Automation #GitHub #OpenSource
To view or add a comment, sign in
-
-
#The_most_expensive_comma_I’ve_ever_typed. 💸 I recently spent way too long debugging a background task that was "failing successfully." No errors in the frontend, no crashes in the logs—just... silence. The culprit? A single trailing comma at the end of a string: #email_body = "Hello there...", In Python, that tiny comma turns your intended String into a Tuple. So, instead of sending a block of text to the email handler, I was sending ("Hello there...",). Because we had fail_silently=True enabled in our background thread (standard practice to keep the UI snappy), the system was quietly choking on the Tuple and dying without a word. #The Lesson: Syntax Matters: Even in a "readable" language like Python, one character changes the entire data structure. The Danger of Silence: fail_silently is a double-edged sword. It keeps the user experience smooth, but it can bury the "why" during development. Log Everything: If it’s failing silently, make sure your logger isn’t! Has a single character ever brought down your entire workflow? Let’s commiserate in the comments. 👇 #Python #SoftwareEngineering #CodingLife #Debugging #Django #WebDevelopment
To view or add a comment, sign in
-
Python mastery isn't just about syntax. It's about leveraging the language to write code that's efficient, readable, and truly robust. We use Python daily — from quick scripts to large-scale systems. But beyond the basics lies a deeper layer of features and practices that can transform your code from simply working to exceptional. As engineers, our job isn't just to ship code. It's to build solutions that are maintainable, scalable, and reliable. Here are 3 underrated Python strategies that have consistently paid dividends in real-world development: 1. Master Context Managers (with Statement) Most developers use with for file handling: with open("data.txt") as f: content = f.read() But context managers are useful anywhere you need safe setup + cleanup: • Database connections • Thread locks • Temporary files/directories • Network sessions • Custom resources Using with eliminates repetitive try/finally blocks and ensures resources are always released — even if errors occur. Cleaner code. Fewer leaks. More reliability. 2. Use Generators for Memory Efficiency If you're processing large datasets, avoid loading everything into memory. Instead of this: numbers = [x*x for x in range(10_000_000)] Use this: numbers = (x*x for x in range(10_000_000)) Generators evaluate values only when needed. Perfect for: • Large files • Streaming APIs • Data pipelines • Infinite sequences • Performance-sensitive apps Lower memory usage. Faster pipelines. Elegant iteration. 3. Embrace Type Hinting Python is dynamic — which is powerful, but risky in large codebases. Type hints make your code clearer and safer: def greet(name: str) -> str: return f"Hello {name}" Benefits: • Catch bugs early with tools like mypy • Better IDE autocomplete • Easier refactoring • Cleaner APIs • Better collaboration across teams For growing engineering teams, type hints are a game-changer. Flexibility + safety = scalable Python. Final Thought Great Python developers don’t just know syntax. They know how to use the language to create systems that last. Small improvements in code quality compound massively over time. What’s one underutilized Python feature that changed how you code? I'd love to hear your favorite hidden gems. #Python #PythonDevelopment #SoftwareEngineering #Programming #CleanCode #DeveloperLife #TechLeadership #CodeQuality #PythonTips #BackendDevelopment
To view or add a comment, sign in
More from this author
Explore related topics
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