21 MORE nooby Python habits

mCoding · Beginner ·🧠 Large Language Models ·3y ago

Key Takeaways

The video discusses 21 nooby Python habits to avoid, covering topics such as code optimization, data analysis, file manipulation, input/output operations, Python best practices, and code readability, using tools like PyCharm, NumPy, Pandas, Pathlib, and JSON.

Full Transcript

welcome to my list of 21 more newbie python habits I'm also giving away pycharm licenses so get your hashtag pycharm down in the comments to enter newbie habits are things that noobs do that doesn't mean they're wrong or bad or that you can't or shouldn't use them but nonetheless they tip off other developers to your inexperience and avoiding them tends to improve your code so whether you're brand spanking new to python or just trying to keep that awesome Tech job you somehow got let's Dive In newbie thing number one manually rounding inside a print statement you computed some value and it's time to print it out but it's a floating point value if you just print it out as is it's too many digits too much clutter so you just round it right instead just use a format specifier number two repeatedly converting to and from numpy arrays often accidentally in most data analysis situations the best thing is usually to just immediately convert your data into numpy arrays or pandas data frames then just make sure you stick to all numpy or pandas functions it's a pretty common mistake to actually use a non-numpy function like the built-in Max which results in even worse performance than using Macs on a list number three manipulating paths as strings for obvious reasons it's very common to represent a path as a string so there's the obvious temptation to do string operations to manipulate the paths but this approach is highly error prone instead consider using the built-in pathlib pathlib already has built-in most of the common file and directory manipulations that you would want to do number four writing i o functions that take the path instead of an i o object there's nothing really wrong with having a convenience function that does this but what you should really do is have a separate function that does all of the writing operations so this function does all of the logic of writing to the file and this function is just a convenient wrapper around it the reason for doing this especially if you're writing a library is that people might not want to open a file or they might want to be writing to a different kind of i o object like to a zip file to a network connection or to a string by providing this version of the function you allow people to write to whatever they want to instead of just to a file and speaking of writing to a string that brings us to our next newbie habit concatenating strings with plus the plus operation on a string copies the string so in this for loop I end up making 100 copies of a larger and larger string instead use a string i o object this uses a growing in-memory buffer to minimize the number of copies of the string data and it has an interface just like a file object that you'd get from open and once you're ready to convert the buffer back into an actual string object call get value number six put a finger down if you've never done this one using eval as a parser through dubious means you've got a string with a data structure in it just pass it to eval what could possibly go wrong well of course the answer is eval is bad and you should feel bad for trying okay okay eval does have some legitimate uses but parsing data from a string isn't one I would probably use in production instead consider using an actual parsing Library like the built-in Json number seven and this one really pains me to see storing your function inputs and or outputs AS Global variables if you're reading from a global and using it to change something about how your function works then consider it might be better if it's just an input parameter and if you're writing to a global variable it should probably be somewhere in your return value hey while you're here did you know that I'm available for Consulting that's right self promo my team does python Consulting Contracting training and interview prep if you're interested visit mcoding.io number eight thinking and an or return bools you may not have ever printed out the results of an and or an or because you typically just use them in if statements but if you did you might have been surprised at the results you don't get a true or false in general ore Returns the first truthy thing or the last falsy thing and and Returns the first falsy thing or the last truthy thing number nine single letter variables there are of course cases where single letter variables are fine a single underscore to denote something calling a loop variable I common conventions like X Y and Z coordinates or even well-known math formulas no what I'm talking about is a whole function where everything is just a single letter or maybe two with just a few carefully thought out variable names it would be so much easier to understand number 10 using both div and mod instead of divmod if you're doing like math I guess there's a decent chance that you'll want to divide by a number and know both the quotient and remainder and that's what div mod does it gives you both a quotient and the remainder without repeating the calculation number 11 not knowing about properties a lot of noobs especially people coming from java are in the habit of writing Getters and Setters for every variable the more pythonic thing is to just leave the variable as part of the public interface but sometimes we use Getters and Setters because we want to actually do something in them in that case having a separate get and set function does make sense but doing that means that in order to access the value I'm now calling functions set X and get X instead of the more intuitive.notation well that's exactly what a property lets us do now because of descriptor magic we can just say object.x equals 42 and that will actually call the setter with the value being 42 and On a related note number 12 having expensive properties cool cool you learned what a property is and now it's time to save two characters on every function call by converting them into properties slow down there it's not about saving characters anything that takes much longer than just a normal attribute access shouldn't be turned into a property if you have a function that might be very expensive offensive make it look expensive number 13 inserting or deleting while iterating here We're looping over the dictionary and while that iteration is in progress we try to delete a key for a dictionary doing this is going to raise a runtime error but for other data types especially see extension types this might just do something very weird and not throw any error replacing or modifying a value on the other hand is typically fine another approach is to keep a set of keys that you're going to delete Loop over the dictionary and add anything that you want to delete into the to delete set then once you're done delete all of the keys afterwards number 14 and I know this will be controversial any use of filter or map the reason is that they encourage you to write code that looks like this in general you can replace any filter like this and you can replace any map like this these generator comprehensions are lazy just like filter and map and they produce the same elements and bonus points if you were just immediately going to convert that to a list instead you could use a list comprehension which is even more readable and it's tomorrow who could have guessed that yelling python into a microphone for two hours was bad for your voice but you're worth it 14 down let's keep going number 15 defining too many or inappropriate Dunder methods some of them like in a knit or a hash make perfect sense to Define for most classes but the person class does not represent any kind of number or thing that naturally has a plus operation associated with it but this code goes ahead and defines IAD to make plus equals mean make these two people friends don't use a Dunder method to accomplish this task just use a normal function with a good name number 16 trying to parse HTML or XML using regular Expressions it's not that you made a mistake that your regular expression is bad or that you're not smart enough to come up with the complete one that handles all the edge cases it's literally impossible to create a regular expression that can parse HTML because HTML is not a regular language instead you're going to need an actual parser you could use something like Python's built-in HTML parser or you could reach for more full featured third-party Library like beautiful soup which of course has a parser inside of it 17. not knowing about raw string literals in most rings it doesn't matter but specifically for Windows paths and in regular expressions using literal backlashes is very common plop down an r in front of your string to make it a raw string literal raw strings ignore Escape sequences making regular Expressions much easier to read 18. thinking that super means parent you might think that the supercall is going to call the roots version of F and in most cases you'd be right but not in all cases and the reason is that someone could inherit from your class this instance of C is also an instance of a but when we call F we see that the chain of super calls goes from C to A to B to root in particular this super column side of a right after printing a dot f sent us to The Sibling class b not to A's parent root I've got a whole video on super if you'd like to hear more 19. passing structured data around as a raw dictionary or Tuple you do some calculation take a measurement or summarize some data if these values are meaningful and always need to stick together then most likely this should be a class and you should give it a name if you were returning a dictionary before a data class is probably what you want and if you're returning a tuple then a named Tuple is probably what you want number 20 using collections named Tuple instead of typing named Tuple back in the day this was a best practice because it allowed you to give Tuple elements good names but nowadays the typing named Tuple is a much more readable way to do the same thing it actually looks like a class definition it's easy to read and doesn't rely on strings and as always saving the best for last number 21 import time side effects please please please don't print something when I import your module even if your library can also be used as a script and that's the behavior that you want when you run the script use the deaf main if name main idiom to hide it behind a main function that's another one where I've got a whole video explaining the benefits of doing this and that's 21. you must really love the sound of my voice or maybe you just like my content in which case don't forget to subscribe and become one of my patrons on patreon pitching for more newbie habits check out my first newbie Habits video as always thank you to my patrons and donors for their support slap that like button an odd number of times and I'll see you next time

Original Description

Get better at Python by ditching these habits. Embrace the Zen of Python and leave your nooby habits behind! Improve your code and your prestige and learn how to master Python. CONTEST CURRENTLY CLOSED! OFFICIAL CONTEST RULES: 1. All entries must comply with the YouTube community guidelines ( http://www.youtube.com/t/community_guidelines) and YouTube Terms of Service (http://www.youtube.com/static?gl=US&template=terms). Entries that violate YouTube guidelines are automatically disqualified. 2. YouTube is not a sponsor of the contest and viewers are required to release YouTube from any liability related to the contest. 3. Privacy notice: no personal data will be collected for this contest. 4. In order to enter, you must (a) be one of my subscribers, AND (b) make a top-level comment to the video including #pycharm somewhere in the comment. 5. The contest is free, there is no fee required to enter. 6. Winners will be chosen randomly 1 week after the date the video went live from all users who have entered and not been disqualified. 7. Each winner will be notified via a comment reply from me that details what prize was won (e.g. "Congratulations! You have won XYZ. Please email me."). I will ask the winner to contact me by email, and I will reply through email with a random token which must be posted as another reply to the winning comment from the winning account in order to verify account ownership and prevent fraud. 8. Each winner will have 72 hours to respond AND prove account ownership or their prize is automatically forfeited and another winner will be chosen. 9. A winner can only win 1 prize per contest. 10. The prize pool for this contest is: 2 licenses ("Free 1-Year Personal Subscription") to any of these JetBrains IDEs: AppCode, CLion, DataGrip, DataSpell, GoLand, IntelliJ IDEA Ultimate, PhpStorm, PyCharm, ReSharper, ReSharper C++, Rider, RubyMine, WebStorm, or dotUltimate. A prize consists of 1 license, which will be delivered in the form of a redeemable co
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from mCoding · mCoding · 0 of 60

← Previous Next →
1 Goodbye, List! Type hinting standard collections - New in Python 3.9
Goodbye, List! Type hinting standard collections - New in Python 3.9
mCoding
2 Python's comma equals ,= operator?
Python's comma equals ,= operator?
mCoding
3 Finding Primes in Python with the Sieve of Eratosthenes
Finding Primes in Python with the Sieve of Eratosthenes
mCoding
4 Find the First Missing Positive Int | Hard Interview Question on LeetCode
Find the First Missing Positive Int | Hard Interview Question on LeetCode
mCoding
5 JSON Tutorial Python | Basic Python Recipes
JSON Tutorial Python | Basic Python Recipes
mCoding
6 Simulating Brownian Motion in Python
Simulating Brownian Motion in Python
mCoding
7 The Single Most Useful Decorator in Python
The Single Most Useful Decorator in Python
mCoding
8 The Fastest Way to Loop in Python - An Unfortunate Truth
The Fastest Way to Loop in Python - An Unfortunate Truth
mCoding
9 Numpy Array Broadcasting In Python Explained
Numpy Array Broadcasting In Python Explained
mCoding
10 Brownian Motion Single Path Zoom
Brownian Motion Single Path Zoom
mCoding
11 Brownian Motion Fractal Zoom
Brownian Motion Fractal Zoom
mCoding
12 Magic Methods - Making Python builtins work with your classes
Magic Methods - Making Python builtins work with your classes
mCoding
13 50 Million Primes In 5 Seconds - Segmented Sieve of Eratosthenes
50 Million Primes In 5 Seconds - Segmented Sieve of Eratosthenes
mCoding
14 The Hottest New Feature Coming In Python 3.10 - Structural Pattern Matching / Match Statement
The Hottest New Feature Coming In Python 3.10 - Structural Pattern Matching / Match Statement
mCoding
15 How Fast is Python's Sort? Performance Testing
How Fast is Python's Sort? Performance Testing
mCoding
16 C++ First Missing Int, faster than 100%!
C++ First Missing Int, faster than 100%!
mCoding
17 [April Fools 2021] Python 4.0! New old print, mandatory static typing, StackOverflow integration
[April Fools 2021] Python 4.0! New old print, mandatory static typing, StackOverflow integration
mCoding
18 Python dataclasses will save you HOURS, also featuring attrs
Python dataclasses will save you HOURS, also featuring attrs
mCoding
19 C++ Sudoku Solver in 7 minutes using Recursive Backtracking
C++ Sudoku Solver in 7 minutes using Recursive Backtracking
mCoding
20 Every PROOF you've seen that .999... = 1 is WRONG
Every PROOF you've seen that .999... = 1 is WRONG
mCoding
21 Python's sharpest corner is ... plus equals? (+=)
Python's sharpest corner is ... plus equals? (+=)
mCoding
22 Binary Search - A Different Perspective | Python Algorithms
Binary Search - A Different Perspective | Python Algorithms
mCoding
23 The Best Way to Check for Optional Arguments in Python
The Best Way to Check for Optional Arguments in Python
mCoding
24 Local and Global Variable Lookup Weirdness in Python
Local and Global Variable Lookup Weirdness in Python
mCoding
25 Efficient Exponentiation
Efficient Exponentiation
mCoding
26 How To Install Python for Data Science
How To Install Python for Data Science
mCoding
27 0.1 + 0.2 is NOT 0.3 in Most Programming Languages
0.1 + 0.2 is NOT 0.3 in Most Programming Languages
mCoding
28 Python 3.10's new type hinting features
Python 3.10's new type hinting features
mCoding
29 Python 3.10's Quality of Life improvements
Python 3.10's Quality of Life improvements
mCoding
30 Introducing mZips! Python Zip and Zip Longest
Introducing mZips! Python Zip and Zip Longest
mCoding
31 Match statement tips
Match statement tips
mCoding
32 Using except: is a HUGE mistake
Using except: is a HUGE mistake
mCoding
33 Python + YouTube API | Automating descriptions
Python + YouTube API | Automating descriptions
mCoding
34 Anaphones, phonetic anagrams
Anaphones, phonetic anagrams
mCoding
35 Cracking passwords using ONLY response times | Secure Python
Cracking passwords using ONLY response times | Secure Python
mCoding
36 Python f-strings can do more than you thought. f'{val=}', f'{val!r}', f'{dt:%Y-%m-%d}'
Python f-strings can do more than you thought. f'{val=}', f'{val!r}', f'{dt:%Y-%m-%d}'
mCoding
37 Diagnose slow Python code. (Feat. async/await)
Diagnose slow Python code. (Feat. async/await)
mCoding
38 Python MD5 implementation
Python MD5 implementation
mCoding
39 Salting, peppering, and hashing passwords
Salting, peppering, and hashing passwords
mCoding
40 x to bool conversion in Python, C++, and C
x to bool conversion in Python, C++, and C
mCoding
41 You should put this in all your Python scripts | if __name__ == '__main__': ...
You should put this in all your Python scripts | if __name__ == '__main__': ...
mCoding
42 Find the Skyline Problem with C++ Solution Explained
Find the Skyline Problem with C++ Solution Explained
mCoding
43 The ONLY C keyword with no C++ equivalent
The ONLY C keyword with no C++ equivalent
mCoding
44 Should you use "not not x" instead of "bool(x)" in Python? (NO!)
Should you use "not not x" instead of "bool(x)" in Python? (NO!)
mCoding
45 Multiple Assignments in Python
Multiple Assignments in Python
mCoding
46 Why I don't like Python's chained comparisons
Why I don't like Python's chained comparisons
mCoding
47 Automated Testing in Python with pytest, tox, and GitHub Actions
Automated Testing in Python with pytest, tox, and GitHub Actions
mCoding
48 You can pip install directly from GitHub
You can pip install directly from GitHub
mCoding
49 __new__ vs __init__ in Python
__new__ vs __init__ in Python
mCoding
50 Metaclasses in Python
Metaclasses in Python
mCoding
51 The easy way to keep your repos tidy.
The easy way to keep your repos tidy.
mCoding
52 Which Python @dataclass is best? Feat. Pydantic, NamedTuple, attrs...
Which Python @dataclass is best? Feat. Pydantic, NamedTuple, attrs...
mCoding
53 Python __slots__ and object layout explained
Python __slots__ and object layout explained
mCoding
54 C++ cache locality and branch predictability
C++ cache locality and branch predictability
mCoding
55 Avoiding import loops in Python
Avoiding import loops in Python
mCoding
56 25 nooby Python habits you need to ditch
25 nooby Python habits you need to ditch
mCoding
57 Python staticmethod and classmethod
Python staticmethod and classmethod
mCoding
58 Building a Python app with Anvil to email me if my website goes down (includes paid features)
Building a Python app with Anvil to email me if my website goes down (includes paid features)
mCoding
59 31 nooby C++ habits you need to ditch
31 nooby C++ habits you need to ditch
mCoding
60 Interviewing the creator of C++, Bjarne Stroustrup
Interviewing the creator of C++, Bjarne Stroustrup
mCoding

This video teaches viewers how to improve their Python skills by avoiding common nooby habits, covering topics such as code optimization, data analysis, and code readability. By following these tips, viewers can write better Python code and improve their overall programming skills. The video provides a comprehensive list of 21 habits to avoid, making it a valuable resource for beginner Python programmers.

Key Takeaways
  1. Avoid manually rounding inside print statements
  2. Use pathlib instead of manipulating paths as strings
  3. Avoid writing IO functions that take a path instead of an IO object
  4. Use list comprehension for readability
  5. Avoid using Dunder methods for tasks that don't make sense
  6. Use an actual parser for HTML/XML parsing
💡 Avoiding common nooby habits is crucial to improving Python skills and writing better code

Related AI Lessons

Spring AI Tutorial — Your First REST Endpoint with OpenAI (2026)
Build a REST endpoint with Spring Boot 3 and OpenAI to create an LLM-powered API, leveraging the power of AI in your applications
Dev.to AI
10 ChatGPT Prompts for Job Seekers: Resumes, Interviews & Career Growth
Learn how to leverage ChatGPT for job searching, resume building, and career growth with 10 actionable prompts
Medium · ChatGPT
Lost in Transcription: The Week the Machine Started Lying
Learn how Whisper AI transcription can be flawed and understand the importance of validation in AI-generated text
Medium · AI
From Sci-Fi to Source Code: Why the Future of LLMs Looks Like Pure Number Theory
Explore how number theory is revolutionizing Large Language Models, enabling more efficient and effective models
Medium · LLM
Up next
5 Levels of AI Agents - From Simple LLM Calls to Multi-Agent Systems
Dave Ebbelaar (LLM Eng)
Watch →