5 Python BAD Practices To Avoid

Поделиться
HTML-код
  • Опубликовано: 15 сен 2024

Комментарии • 131

  • @mateoortega4649
    @mateoortega4649 3 года назад +75

    Hey man, just finished my first website thanks to your flask tutorial. Thank you for taking your time and experience and sharing it with us so that we can learn!

    • @mavdotj
      @mavdotj 3 года назад +4

      is it available for people to see or is it hosted locally on your computer?

    • @mateoortega4649
      @mateoortega4649 3 года назад +6

      @@mavdotj It is currently hosted locally as I still have not published it but in the next few hours il upload it to the web.

    • @dmitryvlasov931
      @dmitryvlasov931 3 года назад

      @@mateoortega4649 did you upload it?

    • @hemanths2230
      @hemanths2230 3 года назад

      How long did it take?

    • @nocodenoblunder6672
      @nocodenoblunder6672 3 года назад

      Can we have a look?

  • @JaycenGiga
    @JaycenGiga 3 года назад +13

    Using a default dict in the mentioned case is not really pythonic either, since there is a counter in the collections module. The code would then become:
    from collections import Counter
    numbers = [ ... ]
    c = Counter(numbers)
    the Counter API offers a lot of additional functionality and is generally to be preferred over the default dict. The default dict should be used when there is some additional work to do on insertion, like it was done in the second case.
    Regarding the context manager: If you catch yourself writing many try-finally blocks, that is normally the moment to use one. You can also implement custom managers for your own classes via the dunder methods `__enter__` and `__exit__`. Those are what is executed by the with statement:
    with Foo(args) as bar:
    baz()
    more or less desugars to
    bar = Foo.__enter__(args)
    try:
    baz()
    finally:
    Foo.__exit__()

  • @gustavoalebranchirod1051
    @gustavoalebranchirod1051 3 года назад +13

    6:25 I think that is better to use the class Counter (from collections as well), which does the exact same as defaultdict, but you don't have to do any for loop.
    >> form collections import Counter
    >> counter = Counter([1, 2, 3, 4, 1, 4, 4, 1, 4, 3, 3, 2])
    >> counter
    Counter({4: 4, 1: 3, 3: 3, 2: 2})
    >> conter = dict(counter)
    >> counter
    {1: 3, 2: 2, 3: 3, 4: 4}
    Nice video

  • @SamusUy
    @SamusUy Год назад +1

    good beginner tips, couple comments:
    - the mutable args is not a bad practice, it's a bug because the code won't work as intended, the usual way to deal with that is to default to None and then check to assign the mutable object
    - the defaultdict is a good tip but if you're counting there's an even more specialized object class Counter that you can use
    - `with open()` works because open() can be used in that fashion but not all classes do, there's a helper called closing() in the contextlib module that helps with that cases

  • @csabamolnar2035
    @csabamolnar2035 Год назад +2

    For the number count one you can also use:
    counts = dict.fromkeys(set(numbers), 0)
    for key in numbers:
    counts[key] += 1
    (although this requires the numbers to be created before the dict, and its not so easily updatable, but still an ok method)

  • @tcgvsocg1458
    @tcgvsocg1458 3 года назад +5

    Start @1:48

  • @kunle009
    @kunle009 3 года назад +5

    Tim literally drops a video everyday... Bless Up Man!!!

  • @sarojkarki6309
    @sarojkarki6309 3 года назад +13

    Alright someone is thinking about intermediate developers! Thanks Tim, these are really helpful!

  • @goranorsolic1000
    @goranorsolic1000 3 года назад +7

    17:25 don't override "keyboards"
    OKAY

  • @marksegall9766
    @marksegall9766 Год назад +1

    In the first example I think of the parameters being passed 'by reference' versus 'by value'. Whats interesting is that the mutable parameter has a lifetime that is not limited to a single call of the function which we would expect for a local variable in the function. Instead the mutable parameter stays in memory and is acting like a static class variable. We could print the memory location of the mutable parameter to see that this is the case.

  • @DevMadeEasy
    @DevMadeEasy 3 года назад +2

    Hello Tim.
    Wow, 🤩 great content as always, thanks for sharing it!🙏🏻
    I just loved it💜!

  • @Theorose80
    @Theorose80 3 года назад +1

    Excellent video. We often learn about what is a "pythonic" way of doing something without an explanation on the reasons behind it, is it a slight difference in performance like with defaultdict and enum, or can bad and unexpected things happen.

  • @Zancb
    @Zancb 3 года назад

    Hi Tim. I love your videos. They have helped me endlessly. But one thing I'd like to call out, is that you use names that are too similar to built-in words, such as "list", "string", and "dict" which may make things very confusing to people who are new to programming (e.g. "Why does he say 'string +='??").
    I'd suggest writing things like "the_list", "new_string", or "my_dict" so that people are more likely to understand that these are custom variables, arguments/parameters, or objects, rather than built-in words that may throw errors when they try to write a program that uses things like "str", "list", and "dict" (etc).
    Thanks again and I hope you have a great weekend!

    • @Zancb
      @Zancb 3 года назад +2

      Oh gosh. And this comment is super ironic because your last section is not overriding built-in keywords! (which you spelled "keyboards" in your lower-3rd btw)

  • @EvilCherry3
    @EvilCherry3 Год назад

    I don’t understand your first explaination.
    - Why a string is not mutable ? What does mutable exactly mean ? From my instinct the problem should be exactly the same for a list and for a string.
    - To make the comparison more fair either both the string and list should be empty or both should be not empty. Here i don’t know if the problem comes from the fact that the list is a list or from the fact that the list is empty.
    - You don’t give any workaround. What should i type instead of “number=[]” in order to return the desired list ?

  • @guitaek4100
    @guitaek4100 3 года назад +1

    For the fourth bad practice I heard that often, that you shouldn't use range. But I don't see a workaround when you need to modify any list as directly looping through the list you cannot set new variables to old values

    • @tomasadams3922
      @tomasadams3922 Год назад

      try using list comprehension, i have tried a few examples and it was always faster than using a for loop

  • @kurwajebana
    @kurwajebana 3 года назад +10

    6:34 I guess a Counter class from collections module would be more appropriate for this case :)

  • @moo_goo
    @moo_goo 3 года назад

    knew a good pprtion of these but now its time to go refactor some code for those mutable default params... whoops.
    need more of these videos! great job!

  • @will2see
    @will2see 3 года назад +3

    Hi Tim! What keyboard do you use? Are you happy with it or would you recommend something else for programming? Thanks!

    • @Anludo
      @Anludo 2 года назад

      Any keyboard will work

  • @trag1czny
    @trag1czny 3 года назад +2

    `defaultdict(lambda: 0)` should be replaced with `defaultdict(int)` imo
    also id, zip, and list are not built-in keywords, rather they're built-in functions

  • @not_vinkami
    @not_vinkami 3 года назад

    6:24 for that I might just as well write
    counts = {key: numbers.count(key) for key in set(numbers)}

  • @decoybuilder
    @decoybuilder 3 года назад

    Great vid, had no idea about setdefault, it's basically a defaultdict when you can't use imported modules.
    Thanks

  • @alban5055
    @alban5055 3 года назад +1

    For the defaultdict section, would the following code also be appropriate:
    counts = {}
    numers = [1, 2, 3, 1, 6, 4, 1, 3, 9, 8, 2, 6, 8,4, 5 ,7[
    for key in numbers:
    counts.setdefault(key, 0)
    count[key] += 1
    or is that the equivalent of checking:
    if key not in counts:
    counts[key] = 0
    counts[key] += 1

    • @omarciano42
      @omarciano42 3 года назад +1

      Why use default dict rather than using Counter from collections? Aren't they doing the same thing in this case?

    • @meikamandoliini
      @meikamandoliini 3 года назад

      Not sure.

  • @fr3du
    @fr3du 3 года назад +1

    Could you give me an advice? Because I don't know what I can do. I'm immediately advanced and I want to make a big project but I can't. It's just too hard. And now I don't know how to get to the higher level. How I can improve my skills without watching next tutorial?
    Should I practise more? Could you help and recommend something? Thanks.

  • @justanothergunguy7146
    @justanothergunguy7146 3 года назад +1

    # Mutable Default Parameter:
    The bad practice here is not having a mutable default parameter: it's actually *mutating* the default parameter in the function body which is bad.
    # Not Using A Default Dict:
    TLDR: Not using defaultdict isn't a bad practice, though not using it in *this specific example* might be, and it is definitely use-case dependent.
    Not using a defaultdict is not a bad practice, though it may be in this specific scenario. The demonstrated use-case is a good use of defaultdict. Some scenarios may require that the program take a different flow if a key does not exist. I'll use the way Flask handles request parameters as an example for this: If a Flask endpoint attempts to access a parameter that does not exist, the parameter dictionary will raise a KeyError. Flask then catches this exception to automatically return a 400 Bad Request response, since a required parameter is missing from the request. This behavior is good, and emulating the same behavior with a defaultdict would require extra checks from the developer, which is exactly what we're trying to avoid in Tim's example.
    # The Last Three: 100% agreed

  • @firstname4337
    @firstname4337 3 года назад +3

    that first one shows that python is freaking stupid at times

  • @johnnytoobad7785
    @johnnytoobad7785 3 года назад

    Five reason to use the code analysis (Linter) features in Pycharm.

  • @richardbennett4365
    @richardbennett4365 Год назад

    One doesn't need to put a trailing underscore after id. It could be a hyphen or a numeral or another letter.

  • @markmadhukar9011
    @markmadhukar9011 3 года назад

    very insightful!! thank you @TechWithTim

  • @natiqueibrar1921
    @natiqueibrar1921 3 года назад

    just an Amazing video for ppl who are getting started with python!

  • @nickchourchoulis
    @nickchourchoulis 3 года назад +6

    previous video: "imports should always be in the top of your code"
    this video: "line 10: from collections import defaultdict"

  • @asaf7132
    @asaf7132 3 года назад

    the solution to the first problem you have mentioned may be declare the mutable object to "None". E.g: "numbers = None

  • @helplearnhome9542
    @helplearnhome9542 3 года назад

    Thanks a lot for context manager

  • @baphnie
    @baphnie Год назад +1

    I understand the behavior of mutable default parameters, but am curious if this behavior is intentional? When would it be useful?

  • @richardbennett4365
    @richardbennett4365 Год назад

    for i, val in enumerate(list):. Well, that's crazy. How does anyone know the first variable, called i, in this case is the index. If the statement were written with the following variable names,
    for value_of_x, value in enumerate (list):, then the index is value_of_x variable. How could anyone know the first variable in the index variable in the for loop?

  • @samr6148
    @samr6148 3 года назад

    Very helpful, thanks!

  • @codeunited5905
    @codeunited5905 3 года назад +2

    The first one is something that happen to me and I didn't even know this sh*t 😑

    • @davidt01
      @davidt01 3 года назад +1

      Happened to me a couple of days ago.

  • @roxx2k356
    @roxx2k356 3 года назад

    Nice tutorial, Small correction in the last part i remember _var means protected variable, __var means private variable.

    • @Zancb
      @Zancb 3 года назад +1

      That's incorrect. Look at Python's documentation for naming variables and functions. The prepended underscore is for private variables.

    • @roxx2k356
      @roxx2k356 3 года назад +1

      @@Zancb If u go through python docs, there it is written that one _ at beginning makes a variable non public but that doesn't mean it is private, do try that in code take example of inheritence u will understand difference b/w private(__) and protected(_).

    • @Zancb
      @Zancb 3 года назад +1

      @@roxx2k356 "Not public" is another way of saying "private". Stop trying to protect your ego by talking around the facts.
      Double leading underscores are usually used for mangling class variables to avoid naming collisions when someone does "from module import *"
      Single leading underscores keeps the variables from a class/import from being readily accessible (in other words PRIVATE).
      Stop needlessly arguing because you're so desperate to be "correct". You're wrong. Move on.

    • @roxx2k356
      @roxx2k356 3 года назад

      @@Zancb Bro, i don't have any ego i just said what i read from lot of sources, anyways they can be wrong but can u explain then how to declare protected variables in python, cause it seems u know some other way around or u are not considering protected variables are a thing in python..??

  • @JamesJon1187
    @JamesJon1187 2 года назад

    3:55 ...Aaah, I see you're a fellow Canadian eh?

  • @rtshadfhab7125
    @rtshadfhab7125 Год назад

    Hey can you make a video going through collections, abc and data structures in python.
    Can anyone explain why sometimes, python will reorder my lists if I’m dealing with large collections on the fly.
    Furthermore, sometimes I feel I’m battling against python to keep a data type. Forcing me to apply unnecessary type hints and conversions 24/7.

  • @samuelsamson690
    @samuelsamson690 3 года назад

    Pls can u do a tutorial on KivyMD
    I really love your intense algorithm
    Thank you ❤️
    Keep the good work

  • @Mukesh-bf1xt
    @Mukesh-bf1xt Год назад

    use Counter(list) for getting dictionary ... no need to write for loop

  • @marasmusine
    @marasmusine 3 года назад

    Oh my gawd I wish i knew about defaultdict years ago.

  • @richardbennett4365
    @richardbennett4365 Год назад

    If he would tell us why an integer type is mutable, but a characteristic type is not, we could better understand why python works this way.

  • @ultratech3078
    @ultratech3078 3 года назад

    Hey can you please make a video on how to make a wordsearch game and algorithm

  • @benjamimmoreira1680
    @benjamimmoreira1680 10 месяцев назад

    Didnt work on mine. Can you help me?

  • @richardbennett4365
    @richardbennett4365 Год назад

    He said, "comma," but he typed a colon punctuation mark at 16:47.

  • @simonelutero6913
    @simonelutero6913 3 года назад

    I think the first one is a really bad feature, why does it have to mantain the link to the same location even when the function ends? It is breaking the local scope logic, I don't get the reason

  • @maxburton7582
    @maxburton7582 3 года назад

    Hello could I code with a 16gb ram, i5 10th gen and a nvida 3060 ?

  • @arcadiosincero
    @arcadiosincero 3 года назад

    Why is that first one even a thing? If I want to be tormented by non-obvious details of the language I’m using, I’d just stick with C++ or JavaScript. At least Python still has more good than bad compared to other common languages.

  • @ultimatejy9393
    @ultimatejy9393 3 года назад

    can I use setdefault in the word count example?
    s = "hello"
    d = {}
    for k in s:
    d.setdefault(k, 0)
    d[k] += 1
    print(d)

    • @mauro_carvajal
      @mauro_carvajal 3 года назад

      yes, you can use it like that but i think is more pythonic with d.setdefault(k,0) += 1, as setdefault already return the d[k]

    • @ultimatejy9393
      @ultimatejy9393 3 года назад

      @@mauro_carvajal i just tried your suggestion, it's not working. d.setdefault(k,0) actually return integer instead of the dict object

    • @mauro_carvajal
      @mauro_carvajal 3 года назад

      @@ultimatejy9393 you are rigth, i have never used the function so i asume it returned d[k] but returns its value, so yeah your initial code is rigth, sorry about that

    • @ultimatejy9393
      @ultimatejy9393 3 года назад +1

      @@mauro_carvajal it's ok... We are all on the path of learning 😊

  • @binaprajapati7709
    @binaprajapati7709 3 года назад +1

    May I know when will your minecraft server on discord be up?

  • @basim1163
    @basim1163 3 года назад

    Bro how did you learn python

  • @eliber
    @eliber 3 года назад

    Thanks 😊

  • @luul4683
    @luul4683 3 года назад

    which font is it?

  • @insidiousmaximus
    @insidiousmaximus 3 года назад

    7:38 subtitles, tee hee

  • @vaibhavsrivastva1253
    @vaibhavsrivastva1253 2 года назад +2

    For all my fellow class XII students, always remember that the 'return' keyword brings the said object/iterable back to your main program, i.e- "return List" will create a list called 'List', containing whatever variables the function has filled it with.

  • @elisachin9330
    @elisachin9330 2 года назад

    great video

  • @AnotherJohnnyJones
    @AnotherJohnnyJones 3 года назад

    How do you feel about using a private variable name with a mutable default parameter? I.e.
    def some_dynamic_prog(x, _memo={}):

    • @mauro_carvajal
      @mauro_carvajal 3 года назад

      an argument should not have a private variable name

    • @AnotherJohnnyJones
      @AnotherJohnnyJones 3 года назад

      @@mauro_carvajal should dynamic programs always pass the initial data structure when called?

  • @dziugazz
    @dziugazz 3 года назад

    Am I the only one that got in the first "problem", the answer 1 [1] 2 [1,2] (like how it's printing) ? (I am kinda new to python)

  • @wr81mon
    @wr81mon 3 года назад

    The infamous Stack Overflow blind copy paste FTW

  • @YotamBarakJAB271104
    @YotamBarakJAB271104 3 года назад +1

    18:09 from builtins import zip as realzip
    Hahahahahaha

  • @kitetm7596
    @kitetm7596 3 года назад

    18:45 what does a private variable mean ?

    • @tornadol6530
      @tornadol6530 3 года назад

      An attribute that is 'locked' inside, encapsulated within a class. Meaning it is only used within the class, it cannot be inherited or used outside of the class

    • @kitetm7596
      @kitetm7596 3 года назад

      @@tornadol6530 oh I see thanks for the explanation

  • @altward2994
    @altward2994 3 года назад

    Great!

  • @tcgvsocg1458
    @tcgvsocg1458 3 года назад

    To the top

  • @nontth5355
    @nontth5355 3 года назад

    First mistake took me an hour to debug.

  • @itzmeB2
    @itzmeB2 3 года назад +1

    I didn't watch the whole or have anything funny to say so I wanna claim my early ticket so
    I say we E

  • @christopheragbodzahmakafui12
    @christopheragbodzahmakafui12 3 года назад

    Thanks Thanks Thanks

  • @gametimewitharyan6665
    @gametimewitharyan6665 3 года назад

    People who do codewars daily might have known the second one ;)

  • @ethiogazeta
    @ethiogazeta 3 года назад

    Yo

  • @sumitpatidar3143
    @sumitpatidar3143 3 года назад +1

    Tim:
    My Mind: my bad habits lead to late night bla bla bla.........

  • @AMIN-yn5nl
    @AMIN-yn5nl 3 года назад

    Best😍😍♥👊🏼

  • @kickflipz
    @kickflipz 3 года назад

    Why are you saying "zed" for the letter z lmfao, then 2 seconds later you say z as just "z"

  • @Crazmuss
    @Crazmuss 3 года назад

    "not a mutable object", "not immutable object", dude, english is so confusing, why do they need those dam articles?

  • @knuttlaarsen7218
    @knuttlaarsen7218 3 года назад

    Can't know how I stopmed onto this. Anyway Damn good video 🙌🙌. I also have been watching those rather similar from MStarTutorials and kinda wonder how you guys make these clips. MStar Tutorials also had amazing info about similiar things on his vids.

  • @keshavsharma9380
    @keshavsharma9380 3 года назад +1

    Aahh.. may I have a heart❤️ sir?

  • @tobeypeters
    @tobeypeters 3 года назад

    That mutable parameter thing is a poor language design thing.

  • @gustavojuantorena
    @gustavojuantorena 3 года назад

    first

  • @DreaminBig
    @DreaminBig 3 года назад

    Your views have gone way down buddy

    • @Zancb
      @Zancb 3 года назад +1

      What's your point?

  • @samsepi0l4
    @samsepi0l4 3 года назад

    First !!!

  • @itzmeB2
    @itzmeB2 3 года назад

    First?

    • @Zancb
      @Zancb 3 года назад

      Wow, you kids still do this? Fun.

    • @itzmeB2
      @itzmeB2 3 года назад

      @@Zancb wow u grandpa's still write this?

  • @tancodes
    @tancodes 3 года назад

    Dear person whoever reads this, Hey, you, yes, I am talking right to you. I hope you will see yourself with the eyes I see you one day, because I can tell you have some awesome music taste :) You’re such a beautiful human being and worth and enough. I hope you know that you do only need yourself to be happy, I know society build up the standard that whenever you’re alone you’re not living a happy live. But in fact that is not true, if you start to realize that you actually deserve all the good things happening to you, you will treat yourself a lot nicer. I hope you let yourself rest, don’t beat yourself up over past mistakes, over regret, and over everything your mind wants to destroy you. I wish I could remove all those demons inside of your head because you deserve to feel happy. If you ever feel lonely then watch the sky, because you know, someone, at the same time is watching the sky too, maybe feeling the same way..I am glad you exist and I hope you won’t ever remove your own spot in this world, maybe you don’t feel like you belong here but, Angel, then build your home here. I don’t want you to leave this world unhappy. I want you to live every little second, I want you to feel alive, I don’t want you to see yourself just existing. You deserve it. Whatever happened, it’s not your fault, the demons in your head recognize that you have a beautiful heart, they want to take it because they have never seen such beautiful heart as yours, so why let them win over you? . You’re not selfish for isolating yourself, but you deserve to talk to someone. If you’re reading this than please never forget to breath and smile.
    Don’t live up to other standards! It’s your story and not theirs.
    Life for those who couldn’t, smile for those who forgot what a genuine smile is, love like there’s no other, hug like it’s your last one.
    I love you and send you hugs.
    You’re so strong, you’re still here, and I am proud of you.
    YOU ARE NOT USELESS. READ THAT AGAIN.
    Enough with beating up yourself for today, okay?! - The stranger that cares about you more than anything. I hope this is enough for you to stay today, tomorrow will be a new day, a new start, let go now. I hope you can stay. This is your sign to stay and treat yourself with love, you deserve it.
    And in case no one told you today, again, I am so proud of you. I
    hope you will remember my words- :)
    Until tomorrow, my friend . Take care! :)

  • @ertagon
    @ertagon 3 года назад +2

    No. 1 Do not program in Python
    No. 2 Repeat step No.1

    • @ixypsylongaming
      @ixypsylongaming 3 года назад +1

      python is cool

    • @ertagon
      @ertagon 3 года назад

      @@ixypsylongaming Skateboards are cool but I wouldn't use them on a motorway.

    • @ixypsylongaming
      @ixypsylongaming 3 года назад +1

      @@ertagon You can do various stuff with python

    • @ertagon
      @ertagon 3 года назад

      @@ixypsylongaming And that's the problem, because no one ever stops to ask if they should.

    • @meikamandoliini
      @meikamandoliini 3 года назад

      public class SunEkaLuokka {
      public static void Main(string[] args) {
      System.out.println("Mitä jäbä leissaa?")
      }
      }

  • @Принуждениекмиру-ь2ц

    Python is a garbage language. The company i work in only has C++ programmers. Maybe we don't know something in this world? Hahah.

  • @neuralwarp
    @neuralwarp 3 года назад

    And there you go. Python is an unsafe language for serious software engineering.