5 Good Python Habits

2024 ж. 13 Мам.
293 501 Рет қаралды

Here are 5 good habits you should consider building in Python.
▶ Become job-ready with Python:
www.indently.io
▶ Follow me on Instagram:
/ indentlyreels
00:00 Learning Python made simple
00:05 if _name_ == ‘__main__’
03:00 main()
04:50 Big functions
08:07 Type Annotations
14:39 List comprehensions
17:22 Outro

Пікірлер
  • A huge thanks to you guys who are sharing more useful habits and pointing out some of the benefits that I left out in the comment section. You help both me and many other developers to understand more about this beautiful programming world! I'm super appreciative when you guys share cool information :)

    @Indently@Indently2 ай бұрын
  • after hour and hours and trainings, someone explains in 3 seconds the role of if __name__ = ''__main__' ,omg, thx a lot !

    @al3csutzul@al3csutzul2 ай бұрын
    • 100000%

      @lfcbpro@lfcbpro2 ай бұрын
    • if I get a script w/o it, I freak out.

      @DrDeuteron@DrDeuteronАй бұрын
    • It’s good practice (like he said), a lot of beginners/beginner orientated videos don’t use it though, because either they’re not writing code big enough for it to matter (most beginners use a single file), or for the beginner orientated videos they just pass over it because it’s not really important for the scope of the tutorial, however I believe its function should be taught a bit more than it is…

      @demonman1234@demonman1234Ай бұрын
    • Still don’t really understand so it’s like if the module is directly imported from the main file then run?

      @dt3688@dt3688Ай бұрын
    • @@dt3688 Sorta. So, the purpose of the if statement is to explicitly check if your file is run as main (When ran directly the interpreter sets the variable __name__ to “__main__”, but when imported it’ll set __name__ to whatever your filename is.) In doing so, whatever you have inside that if __name__ == __main__ statement will be ran ONLY if you directly run that file/script. Otherwise, if you import the file, whatever you have inside the if statement will not be run. This is useful (mostly) for test code, or if your file is meant to run as both an import and a script on its own. This is to keep whatever imports your script from accidentally running the functions in the file. Ex: def PrintSomething(): print(“This will run”) if __name__ == __main__: PrintSomething() In this code, it will only print the string to your console if ran as a script directly. If you import it, PrintSomething() will not run. (Formatting may have broken for youtube with the underscores for name and main, but yk what I meant)

      @demonman1234@demonman1234Ай бұрын
  • Another important thing with main() is the scope. Code run in "if name main" uses global scope and can/will pollute it. Running code in main has the function's scope :)

    @DamienDegois@DamienDegois2 ай бұрын
    • I would argue that this is _the_ most important reason to use a main() function. It's not just a way to make your code look better organised, it has fundamentally different semantics from just putting code in a top-level if-name-is-main

      @ianroberts6531@ianroberts65312 ай бұрын
    • True, but you should never ever run a main function AND THEN run extra code in the global scope later, so namespace pollution doesn’t rlly matter.

      @Thebiggestgordon@Thebiggestgordon2 ай бұрын
    • I didn't think about that, the arguments in the video didn't convince me at all, but this is a really good reason to use a main funciton.

      @leschopinesns100@leschopinesns1002 ай бұрын
    • What do you mean by "pollution"?

      @AmodeusR@AmodeusRАй бұрын
    • @@AmodeusR I think he means having a bunch of variables exposed to the global scope is polluting it, and can be problematic when importing a module.

      @leschopinesns100@leschopinesns10029 күн бұрын
  • Just one thing about list comprehensions: they can very easily become very hard to read, so I'd say "don't overuse them"

    @farzadmf@farzadmf2 ай бұрын
    • A way to avoid them becoming unreadable without resorting to loops is to split the transformations into multiple separate list comprehensions on new lines, and assigning the result of each line to a variable with a descriptive name to show what the intermediate state represents. Ideally you would use generator comprehensions as well for the intermediary steps and only convert to list at the end (if it's even needed in list form at all).

      @LittleLily_@LittleLily_2 ай бұрын
    • One major example I've seen, unless you've got a very descriptive comment attached or it's doing a super simple operation, don't put two for loops in one list comp

      @Imperial_Squid@Imperial_Squid2 ай бұрын
    • Exactly!

      @farzadmf@farzadmf2 ай бұрын
    • It depends how you use them. Variable Naming has a huge impact in readability as well. For example: taking the person names > 7 case, if we were to rewrite with more descriptive names it can convey a sense of reality and make the code more relatable to the readers. listLongNames = [ pp for pp in people if len(pp)>7 ] See, makes so much difference.

      @GoswamiSagarD@GoswamiSagarD2 ай бұрын
    • ["["".join(letter) for letter in word if letter.isalpha()] for word in "why would you say that?".split() ]

      @DrDeuteron@DrDeuteronАй бұрын
  • A main(with parameters) is even more useful when testing. Allow the if __name__ block to handle command line arguments and then pass sanitized versions of those to your main. Then your tests can just call main directly and test various scenarios.

    @Aplysia@Aplysia2 ай бұрын
    • I'm just learning python, but if you were to do this, how would you suggest you test your input parsing and sanitation itself? I'm thinking I'd have the '__name__' block call a 'parse_and_sanitise_inputs' function to do that (and pass its results to main), which could then be tested separately.

      @mnxs@mnxs14 күн бұрын
  • Slight tweak to this main() thing. I think its better to have main return an int and then have sys.exit(main()) in the if name == main bit. That way the program behaves like a normal commandline program with an exit status. You can add in error handling and return a non-zero exit status easily this way.

    @666ejames@666ejamesАй бұрын
    • That's a useful tip if you're building a more complex script, but probably a bit outside what I'd put in a boilerplate.

      @pseudotasuki@pseudotasuki19 күн бұрын
  • Hats off to my main man Bob, he did nothing wrong.

    @PikalaxALT@PikalaxALT2 ай бұрын
  • 4:11 thanks for this. Structuring my code to have a main function that runs the others and an if statement that runs main is a great idea to clearly show what the program does.

    @justwatching1980@justwatching19802 ай бұрын
  • Super appreciate this. Need to include type hinting into my coding. Your explanations make sense.

    @mathewrtaylor@mathewrtaylor2 ай бұрын
  • For number 2, another bonus is if you declare a main function you can expose it in an init or import it. One example is importing when testing.

    @AnthonyFammartino@AnthonyFammartino2 ай бұрын
    • Another bonus is containing the variables. You won't accidentally use a globally-scoped name in another function, if that name is local to the main instead

      @jamesarthurkimbell@jamesarthurkimbell2 ай бұрын
    • Thanks for sharing the benefits guys! I often forget to mention simple things like these when creating the videos as a one man team.

      @Indently@Indently2 ай бұрын
    • It's similarly useful if you're using asyncio.

      @pseudotasuki@pseudotasuki19 күн бұрын
  • At 10:45 it is better to use Iterable from the typing module to annotate "elements". This way you could pass not only lists but also tuples or even generators.

    @artyom7891@artyom78912 ай бұрын
    • it's called duck typing.

      @DrDeuteron@DrDeuteronАй бұрын
    • @@DrDeuteron yes but the point of type hinting is to reduce the issues you have with duck typing. Duck typing is both a strength and a weakness of Python. And better type hints are more meaningful so it is encouraged to use type hints imported from the typing module.

      @nathanrasmussen931@nathanrasmussen931Ай бұрын
    • @@nathanrasmussen931 i agree, especially containers vs iterables, but what do you do for a function that takes floats, int, all the numpy versions, or arrays, matrix etc…is there super that covers all that?

      @DrDeuteron@DrDeuteronАй бұрын
  • Comprehensions come in various flavours. There are also set { x for ...} and dict { kev: value for ...} comprehensions, as well as generator expressions ( x for ...) . The latter is interesting if performance matters and you know that you traverse the result at most once. Exceptionally good for loading tuple data into polars or pandas for example.

    @pUrbanNinja@pUrbanNinja2 ай бұрын
  • for list comprehensions: a lot of common patterns can be covered by `filter` and `map`. For example, instead of doing [p for p in people if len(p) > 7] you can do filter(lambda p: len(p) > 7, people) which I find quite a lot more readable because it's explicitly telling you that the only thing happening in this statement is we're getting rid of some values based on a predicate.

    @KingJellyfishII@KingJellyfishII2 ай бұрын
    • list(itertools.compress(people, map((7.).__lt__, map(len, people))) or functools.partial(operator.lt_, 7). which I like because it tells people to stay tf out of your code.

      @DrDeuteron@DrDeuteronАй бұрын
    • @@DrDeuteron ahahahahhaha

      @kuark5290@kuark5290Ай бұрын
    • ​@@DrDeuteronlol

      @fuchrr4519@fuchrr4519Ай бұрын
  • This came at PRECISELY the right time for the type annotations stuff 🎉 big thanks

    @damien__j@damien__j2 ай бұрын
  • Another great video with great examples. Thank you. Mypy, who knew?

    @michaelrstudley@michaelrstudley2 ай бұрын
  • I've been following you for few months now, you provide amazing content, and I really appreciate your videos. Thank you so much. You are helping so many students😊

    @alexlim6968@alexlim696826 күн бұрын
  • Excellent video @Indently. Keep going

    @JulioHOR@JulioHOR2 ай бұрын
  • Thanks so much for the great video on good Python habits. I know you put a lot of time and effort into it, and it shows. The video is well done and easy to understand.

    @shri4r@shri4rАй бұрын
  • Cool video! These are great tips, but I want to point out that IMO there’s some nuance to be had with your “big function” tip, it’s important to recognize there’s costs that come with extracting code. Oftentimes you are never going to use that functionality again, extracting that code can actually make it more difficult to find certain logic just by increasing the sheer number of functions and lines of code, and it will inevitably take additional time and effort to do this extraction which can often be better used elsewhere. Reusable small functions are great, especially in large collaborative projects, but there are plenty of times where the overhead just isn’t worth it. Generally I find it isn’t worth it to abstract functionality until I actually need it somewhere else or if the function is unreadably long, and in that case you often also want to extract it into its own module

    @emmafountain2059@emmafountain20592 ай бұрын
    • Definitely agree. I also think the example function was not "big," at only seven lines and two if statements. Breaking up big functions is often good, but I probably would have left this example function alone.

      @TheFwip@TheFwip17 күн бұрын
  • In the case of making [p for p in people if len(p) > 7] more understandable inherently, I would opt for naming, such as 'n', 'name,' 'name_str' .. [name for name in people if len(name) > 7]. Great vid!

    @GereBear85@GereBear852 ай бұрын
  • Thanks so much for this video. You're such a life saver. Coming from an environment of using c++, I always dreaded the time I would run into an error when I run my python program simply because my editor couldn't catch the errors when I wrote them. Now with type annotations and mypy, I can begin to truly appreciate the power and simplicity of python.

    @user-ou7hd1zi2i@user-ou7hd1zi2i2 ай бұрын
    • I'm incredibly happy to hear you enjoy the type annotations :)

      @Indently@Indently2 ай бұрын
  • having an actual main method and nothing else under the main check is actually very good practice. it allows for easier unit testing especially when using command line arguments, as you can call the main method the same way it would be called from the cli it is not possible if you actually code under the check

    @zangdaarrmortpartout@zangdaarrmortpartoutАй бұрын
  • Thanks a lot for the advices!!

    @analfabetorockebens@analfabetorockebensАй бұрын
  • I’m glad! Your videos become my scripts raise to another level

    @mellolta@mellolta2 ай бұрын
  • Very nicely put together, thanks!

    @ki6fzb@ki6fzbАй бұрын
  • the 4th tip is pretty useful, thank you

    @thaimeuu@thaimeuu2 ай бұрын
  • Today I encountered the first problem while I was learning Python. Surprised to see this video popped up to my scroll and I’m glad I watched this.

    @Rossilorenzo-yf7oq@Rossilorenzo-yf7oq2 ай бұрын
  • great content! subscribed.

    @harley_462@harley_462Ай бұрын
  • That is a awesome kind of tips 👌

    @krzysiekkrzysiek9059@krzysiekkrzysiek90592 ай бұрын
  • I've never used type annotations because it never had any functional effect on the program, I've always worked in a team of one and I always just used vim, so had no syntax analysis. Also, I started with Python 2.6 and don't tend to catch up with new features. This is definitely something I need to work on, along with commenting my code more (or even at all).

    @TheJaguar1983@TheJaguar19832 ай бұрын
  • Well using main is not just prettier / more java like, it allows you to call the module externally from elsewhere which you can't do with the if statement. So there's a practical reason to do it, assuming you do intend to allow it to be called.

    @davidmurphy563@davidmurphy5632 ай бұрын
    • yeah but there is no point in calling a main from somewhere else! If you need to do that, the function you wrote is not a main.

      @philippk5446@philippk5446Ай бұрын
    • @@philippk5446 Often there is a point, especially with scripts. Last week for example I wrote a simple script which sends a request to update a product. I called it update product and gave it a main. It's Django so the usual entrance is run() in terminal but I also call it from admin which runs main. Then I have another update products which loops through the products and updates each one. Point is, the same script is being called from numerous places - sometimes main, sometimes not - so, yes, there is very much a point.

      @davidmurphy563@davidmurphy563Ай бұрын
  • This is a good video and you absolutely should use type annotation. Type annotation will not help the user as stated in the video. The user most likely will be interacting with an app of some sort. Type annotation help developers who will use your code and help you, if you are using the function somewhere else in the code or reusing the function. Documentation will definitely help developers and in some instances can be used to create help for the end user.

    @EAenergy@EAenergyАй бұрын
  • For the first two tips i would encourage to write real tests instead of "tests inside a module". Yes, it will take extra time, but will serve much better.

    @uuuummm9@uuuummm92 ай бұрын
    • how about a video on unittest or the current most bestest argparse?

      @DrDeuteron@DrDeuteronАй бұрын
  • Nice video! Can you make a video about pypi? It has become difficult and confusing to publish a python package, it would be appreciated if you make a tuto about it! Thank you!!

    @benitmulindwa8009@benitmulindwa80092 ай бұрын
  • Thanks for the information

    @nextisnowmain@nextisnowmainАй бұрын
  • I've always loved list and generator comprehensions. I often each part on it's own line because I feel it becomes more readable. For example: [ p for p in people if len(p) > 7 ]

    @TheJaguar1983@TheJaguar19832 ай бұрын
    • Came into the comments to add this. Comprehensions, whether list, dict, set, etc., are much more readable if on multiple lines and you can even add more conditions, though I would advise for moderation.

      @ValkoinenShiro@ValkoinenShiro2 ай бұрын
    • @@ValkoinenShiro I tend to be guilty of overdoing it; almost like I'm trying to win an award for fewest statements. There's a point at which a generator function is cleaner and more readable.

      @TheJaguar1983@TheJaguar19832 ай бұрын
    • @@TheJaguar1983 "clever" is not a compliment in python

      @DrDeuteron@DrDeuteronАй бұрын
  • I really like the "big functions" part but I have a few questions: 1. how do I tell the difference between more "top-layer" functions and these small mini functions that just make things more abstract? i mean, in terms of naming, often you would want to be bale to have a good hierarchy of this. 2. I'm not sure if this example is the best because one also needs to understand at which point should this separation happen. In practise the example probably should stay as it is, so that the code doesn't become more complex and hard to read.

    @somnvm37@somnvm372 ай бұрын
  • 9:50 before you use a function, you should know, what it does. And you can insert every type which provides an upper-function and not only strings.

    @ThomasVWorm@ThomasVWorm2 ай бұрын
  • Very good video. Thanks

    @nelsin11@nelsin112 ай бұрын
  • Love your videos :)

    @user-zz7xz2up9x@user-zz7xz2up9x2 ай бұрын
  • Question: how can i do a type annotation for a function passed as a parameter of annother funcion? Ex: def do_this(arg: float): return blablabla with arg def do_that(arg: float): return blobloblo with arg def what_to_do(arg: float, func: >Type that i wanna know

    @vitorlopes9967@vitorlopes9967Ай бұрын
  • Thank You!

    @riteshkarmakar3597@riteshkarmakar35972 ай бұрын
  • Excelente video.

    @lucas5nov@lucas5nov2 ай бұрын
  • You can overdo the whole "small functions" thing and I think this is actually a perfect example of when not to do that. Unless you reuse the functionality elsewhere, don't extract the logic into it's own function bc it's much easier to read code that hasn't been spread out all over the codebase for no good reason. If you must have a predicate function with a descriptive name, just make a lambda. "You never know" is a good way to pollute the codebase with functions that are called in like one place. Plus, naming is hard and the more functions you create, the more likely it is that you have semantic inaccuracies in the names.

    @ratfuk9340@ratfuk934023 күн бұрын
  • Python is fun to code in, and you can do a lot of stuff - but I usually end up porting those ideas back to C. Cython is a nice blend sometimes but meshing them together can be a little painful in my experience. Probably a skill issue (on my part ofc) 😅

    @Crux161@Crux1612 ай бұрын
  • Thank you for your video. Maybe a bit off-topic here, but how can I get the green run-arrow next to the line-number? It isn't here in my VS Code.

    @pylsur2024@pylsur20242 ай бұрын
    • This looks a lot more like IntelliJ than VS Code to me

      @Schaex1@Schaex1Ай бұрын
  • As someone who learned C before python, I immediately looked up if I could create an "int main()" equivalent, thus I always used the if __name__ == '__main__' out of habit and preference

    @drow488@drow488Ай бұрын
  • Thank you, actually, I find this video is very very useful to me.😁😁😁

    @davidlu1003@davidlu10032 ай бұрын
  • One additional tip for type hinting: You can still use them even if you need to maintain compatibility with older versions of Python. Instead of putting the type hints inline, you can add them to a "stub" file. It's a bit more work to build and maintain, but it gets the job done.

    @pseudotasuki@pseudotasuki19 күн бұрын
  • Some good tips there, many thanks! I always wondered about the if __name__ == ‘__main__’: line, what was the real advantage in doing that, but you explained it really well.

    @daveys@daveys2 ай бұрын
    • The advantage is to support bad habits.

      @ThomasVWorm@ThomasVWorm2 ай бұрын
    • @@ThomasVWorm - as far as I now understand it, if you call the function from another program, it’ll not run anything in the __main__ section.

      @daveys@daveys2 ай бұрын
    • @@daveys no. The import statement executes all the code, which is why you do have functions at all, because it executes all the def-statements too. This all happens before you do call one of those functions. If the file is meant to be imported, it makes no sense at all to have code in the main body of file which you don't want to run. So with if __name__ ... you prevent code from being run which should not be there at all.

      @ThomasVWorm@ThomasVWorm2 ай бұрын
    • @@ThomasVWorm - Ahh, I get it…hence your comment about bad practice! Thanks!!

      @daveys@daveys2 ай бұрын
    • @@ThomasVWorm you're just no using it right.

      @DrDeuteron@DrDeuteronАй бұрын
  • Very good tips, thank you. It would be useful to copy/paste some of the code demonstrated, as I'm slow/bad at typing. :-)

    @Richard-ck7sr@Richard-ck7srАй бұрын
  • Thank you for your great videos about Python programming. Since I love functional programming, would you please tell us about Python's functional features, map and filter, for example?

    @williammcenaney1331@williammcenaney13312 ай бұрын
    • try some itertools, though I don't know if that is formally functional. Don't forget lambda.

      @DrDeuteron@DrDeuteronАй бұрын
    • @@DrDeuteron Amazon sells some books about functional programming in Python, But Python isn't purely functional. It's object oriented. In a purely functional language, there are expressions instead of statements. To simulate looping, you need recursion. Since each thing is an expression in a purely functional language, each "if" expression needs an else clause, even when you wouldn't need one in a procedural language. That's because each expression must reduce to a value. So suppose I write this: if even n then n else n + 1 Then the number will replace the "if," "then," and "else" expressions. And the computer will remember the number until your program terminates.

      @williammcenaney1331@williammcenaney1331Ай бұрын
    • ​@@williammcenaney1331 week, if you're going to try, you'll need: sys.setrecursionlimit

      @DrDeuteron@DrDeuteronАй бұрын
  • Please make video how actually behind the scenes in python, series of memory allocation initiated after execution of any function, recursion function, closures, and decorators. I'm confusing whenever I visualizes all of this things in my mind.. Please make our foundation clear.

    @wonderfulworld1128@wonderfulworld11282 ай бұрын
  • For the self-documentating part around 11:30 ish, does this only work with PyCharm?

    @CayoBuay@CayoBuay3 күн бұрын
  • Thank you for posting. Just one comment: @4:57, you begin describing "big functions" with type annotations(also called type hints), but you describe type annotations afterwards in the next section. Shouldn't you change the order around to describe type annotations before you describe big functions?

    @astrobullivant5908@astrobullivant59082 ай бұрын
    • Could have been a more clever approach, yes :)

      @Indently@Indently2 ай бұрын
  • I think the best reason to make a main function is the fact you can push utility functions to the bottom of the file and leave the *main* code at the top, not needing to scroll down to see the what the actual main code is.

    @AmodeusR@AmodeusRАй бұрын
  • what ide/editor are you using?

    @nezubn@nezubnАй бұрын
  • Everything was solid up to the p for p in people I don't use any single character variables anymore it doesn't help with readability and I'm not trying to minify everything if the goal is to make it readable. I would just use a list comprehension when absolutely necessary.

    @Websitedr@Websitedr2 ай бұрын
    • I agree, but sometimes there's too much redundancy, and the expression is simple enough that's it's obvious at 1st glance what the single-char var is

      @Rudxain@Rudxain2 ай бұрын
  • is it an extension what says '1 usage', '2 usage' in the functions?

    @nicospok@nicospok4 күн бұрын
  • don't use "..." for a placeholder, use "pass".

    @chyldstudios@chyldstudios2 ай бұрын
    • Whats the advantage of pass vs …?

      @NathanSMS26@NathanSMS262 ай бұрын
    • @@NathanSMS26 I think pass is more visually obvious than the ellipse, but if you prefer the ellipse, then enjoy :)

      @chyldstudios@chyldstudios2 ай бұрын
    • Actually, the best practice is to throw a not implemented error so you don't forget about it.. Honestly though, it's too much effort. I always thought python should have a keyword for this, something nice and short that throws an exception.

      @davidmurphy563@davidmurphy5632 ай бұрын
    • ​@@davidmurphy563 "assert false"

      @Zaniahiononzenbei@Zaniahiononzenbei2 ай бұрын
    • @@Zaniahiononzenbei Oh, that's a good one! I'm going to use that!

      @davidmurphy563@davidmurphy5632 ай бұрын
  • Besides comprehensions I prefer to use map or filter. I am not sure, but I think it's faster

    @sergiofernandeztesta6433@sergiofernandeztesta64332 ай бұрын
  • We can use filter function for the last one too long_names : list[string] = filter ( lambda name : len(name) > 7 , names)

    @mzl1610@mzl1610Ай бұрын
  • which software are you using(compiler)?

    @king_of_daldar143@king_of_daldar143Ай бұрын
  • out of curiosity, why did you say the “psvm function we used to love”. I’m a student and we’ve worked a lot with Java - are things moving away from the language?

    @sultown4343@sultown4343Ай бұрын
  • Awesome.

    @norbertdapunt1444@norbertdapunt144425 күн бұрын
  • OMG!!! He said Java!! I leave!!!

    @azamatkuzdibay9411@azamatkuzdibay94112 ай бұрын
  • Love this video. For the past 2 years I don't know how many times I've been helping my friends, who learn Python, to find a bug. And at the end the bug was simply using str int instead of int str. Also list comprehensions are super cool. My friends for some reason love writing list(filter(lambda ..., map(lambda ..., data ))) when you could just [int(n, 2) for n in data if len(n) == 8]. Also splitting big functions into smaller can sometimes be replaced with list comprehensions too. For example when you need to change data type with some specific data editing. While function is reusable, sometimes its functionality is very specific and unless you are good at naming things, small functions will be littering the code instead of helping

    @cosy_sweater@cosy_sweater2 ай бұрын
    • The filter/map approach is nice to write when coming from other functional programming languages. You're right that they're not always as nice to read as list comprehensions, but in certain contexts they can make a lot of sense since they allow for greater re-useability than comprehensions. Say for example you already have a function that verifies someone is an adult like so: def is_adult(person): return person.age >= 18 And that you have a function that returns the full name of a person like so: def full_name(person): return f"{person.first_name} {person.last_name}" Then at some point you want to take a list of people, and get the full names of everyone who's an adult. With list comprehension, if you wanted to re-use your existing functionality you would write the following: adult_full_names = [full_name(person) for person in people if is_adult(person)] Whereas with map/filter since they already expect functions, you dont need to invoke them, just pass them as is: adult_full_names = map(full_name, filter(is_adult, people)) Obviously I left off the list() conversion in that, but in most cases with functional-style code you wouldn't be converting to lists very often, since leaving the data in generator form is much more efficient as each element can be streamed through multiple transformations without creating a bunch of intermediate lists. It allows you to write your code as if python was a lazy language like haskell, where values are only calculated when they're actually used/required. So basically I would use map/filter if I already have functions for the transformation I'll be doing, but if I would be having to write a lambda inside the map/filter, then I would instead use a list comprehension (or more likely a generator comprehension, again for performance reasons).

      @LittleLily_@LittleLily_2 ай бұрын
    • I was thinking about filter while I was writing the list comprehension, but the instant benefit of using the list comprehension for me was that I could write it out in a split second, while with filter I always need to hover over the function to see the little pop-up with the documentation to make sure I'm passing in things in the correct order.

      @Indently@Indently2 ай бұрын
    • @@LittleLily_ That is a very good point. In my example I pointed on using map() and filter() with lambda-functions. Usually those lambda-functions make code hard to read. I thing using existing functions is very clean Also I was talking about people, who is new at Python. So usually I can see my friends making map -> filter -> ... -> filter combinations. In such cases even using existing functions does not save readability. My point was that beginners sometimes make overcomplicated map/filter combinations that can be replaced with a single much more readable list comprehension

      @cosy_sweater@cosy_sweater2 ай бұрын
    • @@Indently that's fair enough. the order of the arguments for higher order functions in any language generally always has the function first and data second, as that way you can more easily partially apply the function, for example with python you might write this: from functools import partial def full_name(person): return f"{person.first_name} {person.last_name}" people_to_full_names = partial(map, full_name) And now you have a reusable function that can operate on any list of people to return the full name of all of them like so: full_names_a = people_to_full_names(people_a) full_names_b = people_to_full_names(people_b)

      @LittleLily_@LittleLily_2 ай бұрын
    • @@cosy_sweater "pointed" --> "punted" maybe?

      @Graham_Wideman@Graham_Wideman2 ай бұрын
  • The best __name__ = 'main' explanation i've ever seen and im writing this comment just 2 minutes in the video.

    @MuhammadAli-du2zy@MuhammadAli-du2zyАй бұрын
  • Holy cow, didnt know about type annotations!

    @RussellTeapot@RussellTeapot5 күн бұрын
  • Thanks.

    @Pankaj-Verma-@Pankaj-Verma-2 ай бұрын
  • your editor shows the number of usages at the beginning of the function. I have googled(clearly the wrong words) to figure out how to turn that on in Pycharm. Hints?

    @gordofat2911@gordofat29112 ай бұрын
    • Mine PyCharm does this by default

      @kosvkos@kosvkos2 ай бұрын
  • How do you configure pycharm to check types with mypy ?

    @mathieuletrone1249@mathieuletrone12492 ай бұрын
    • There's an extension in the settings that you can install

      @Indently@Indently2 ай бұрын
  • I do appreciate list comprehension

    @hlubradio2318@hlubradio2318Ай бұрын
  • what is your code editor? I use Anaconda / Spyder, and do not see that in use here...

    @xlerb_again_to_music7908@xlerb_again_to_music79082 ай бұрын
    • That's pycharm

      @levoid9187@levoid91872 ай бұрын
  • The point of 2 isn't a "feeling" or anything like that. It's: a) testable, and b) importable from another package.

    @centerfield6339@centerfield6339Ай бұрын
  • You should use `List` from `typing`, insted of `list` to make linters work well.

    @vindexins@vindexins22 күн бұрын
  • I love you! I have been programming in python for around 7-8 years and been using all of those and it is so nice to know that I am not the only one🤝

    @ophirn.m7817@ophirn.m7817Ай бұрын
  • Putting anything in ___main___ instead of main() is dangerous because variables in ___main___ will have a script-wide scope instead of function-wide, which can lead to surprizes. It's best to use ___main___ just to call main() unless global variables are intended.

    @Amonimus@Amonimus23 күн бұрын
  • 16:50 - true. You could use Ruby instead to have nicer code: long_names = people.select{|p| p.length > 7} and if you need them in upper case too: long_names = people.select{|p| p.length > 7}.collect{|p| p.upcase}

    @ThomasVWorm@ThomasVWorm2 ай бұрын
    • you could also use filter an map in py, iirc

      @schwingedeshaehers@schwingedeshaehers2 ай бұрын
    • similar to how you'd write it in JS/TS: longNames = people.filter(p => p.length > 7) longNames = people.filter(p => p.length > 7).map(p => p.toUpperCase()) the lambda syntax in python isn't quite as nice, so I think that's why most people don't like using stuff like map/filter over list comprehensions in python.

      @LittleLily_@LittleLily_2 ай бұрын
    • The problem with list comprehensions is not the syntax but how you layout the comprehension. I prefer to put everything on a new line as it makes it more readable: long_names = [ p.upper() # list element for p in people # iteration if len(p) > 7 # condition ] and it is more readable then using filter and map.

      @mac68tm@mac68tm2 ай бұрын
    • @@LittleLily_ why does "p =>" appear in every call signature? what else is there? seems like redundancy...Guido don't like.

      @DrDeuteron@DrDeuteronАй бұрын
    • @@DrDeuteron Its no different to the |p| in the ruby example, it's just how you define an anonymous function with an input argument named p

      @LittleLily_@LittleLily_Ай бұрын
  • Perfect

    @DariushTasdighi@DariushTasdighi2 ай бұрын
  • I'd leave if you said C#(or some DephiCase language). but Java or Haskell would intrigue me.

    @alexsandrzhemanov5710@alexsandrzhemanov57102 ай бұрын
  • Hi, i have a quastion. Why you use "-> None:" in functions?

    @user-ym2ut1cr3e@user-ym2ut1cr3e2 ай бұрын
    • " -> type " indicates the type of the return value. When the function doesn't return any value, the annotation must be " -> None "

      @juanjosefarina@juanjosefarina2 ай бұрын
  • 16:18 that's a somewhat new way of writting list comprehension for me i always thought it'd only work with [p if len(p) > 7 for p in people]

    @somnvm37@somnvm372 ай бұрын
    • that syntax is incorrect

      @senzmaki4890@senzmaki48902 ай бұрын
    • this is a much better way to make your program crash

      @AdamCallison@AdamCallison2 ай бұрын
  • @Indently how did you get pycharm to look like that?

    @yoseframmal8716@yoseframmal87162 ай бұрын
    • They have a new feature called NewUI

      @Indently@Indently2 ай бұрын
  • i dont quite get def function definition with ->

    @Ginkoman2@Ginkoman26 күн бұрын
  • 3:10 java mentioned, i'm triggered 😂

    @carlpittenger@carlpittenger2 ай бұрын
    • 👍

      @rishiraj2548@rishiraj25482 ай бұрын
  • Regarding Big Functions. It sounds really similar to the argument that you should write all your small functions directly in cython. That way even if performance is not a concern right now those functions can be reused in potential other future parts of the code where performance might matter making your code more reusable. To that I would say: stop it, get some help. Just write the code and after it works if you see you have a performance bottleneck or a good reason to split off functions (code duplication or wanting to test only a part of a function) than do the work instead of always doing it prematurely. Stop optimizing for potential future scenarios at the cost of the present.

    @EmperorRobin@EmperorRobin2 ай бұрын
    • My only recommendation is that you plan your code before you write your code. Living in the moment is only advised if your program is as big as printing "hello, world".

      @Indently@Indently2 ай бұрын
  • Is the pip mypy also available for vscode?

    @ultimateownsz@ultimateownsz2 ай бұрын
    • It is indeed

      @Indently@Indently2 ай бұрын
    • @@Indently thanks for your fast reply! Btw I have a discord server made for friends who also learn python and your channel have great tips on how to learn python faster. So thank you for your teaching in a way! It is accessible and easy to understand :)

      @ultimateownsz@ultimateownsz2 ай бұрын
    • Solarlint extentions give clear check and hints, try it

      @coladock@coladock2 ай бұрын
  • which color theme are you using?

    @ianyang8799@ianyang87992 ай бұрын
    • that is the default theme of pycharm

      @0MVR_0@0MVR_0Ай бұрын
  • pretty good vid. Not a fan of the "is_bob" function as it has hard coded value in the function name without describing what it does. I would prefer something like is_blacklisted with a bliacklist: list[str] = ['bob'] inside or someplace where it can be obtained. Now you don't need to refactor if the name is really "Robert"

    @coneryj@coneryj2 ай бұрын
    • is_blacklisted is a much better real world example. It was supposed to be an amusing example where in this world Bob was the only one that would ever be blacklisted. But yes, in real life, you'd probably have many more people blacklisted than just Bob :)

      @Indently@Indently2 ай бұрын
    • @@Indently agreed.. I know what you were doing and it was a good point. I was just throwing in some additional contribution. You'd be surprised (or maybe you wouldn't) at just how bad function naming and structure can be and how it can impact changes to program requirements

      @coneryj@coneryj2 ай бұрын
    • For sure :)

      @Indently@Indently2 ай бұрын
  • For type annotations, you can also use a .pyi file.

    @bollybigglo@bollybiggloАй бұрын
  • Maybe I'm a beginner but what is the reason to have "main " between""__"" ? Is there any use. Further more why did you not have error when checking if __name__==__main__ As __name__ as no value affected

    @omatousou@omatousou2 ай бұрын
    • __name__ is automatically set to "__main__" when the script is run normally. If it is imported, __name__ is a different value which I'm not entirely sure about.

      @want-diversecontent3887@want-diversecontent38872 ай бұрын
    • By default, the name of the Python main module is always "__main__", i.e. when it is being run as a script. If it were to be imported, the __name__ when become that of the module.

      @birdie123@birdie1232 ай бұрын
    • variables with trailing underscores are understood as a special type, and are already declared and initialized when the script runs. '_name_' will adopt the string name of the current module which defaults to '_main_' if the script is being run directly. Otherwise the string will take the name of the import during execution. so when the script executes and name is not main (in other words the code was imported), the code block to run on compiling will be skipped, and the program will act as an object.

      @0MVR_0@0MVR_0Ай бұрын
  • I know this is just a quick example, but I'd argue a function like is_blacklisted or similar would be better than is_bob. You wouldn't want to add another function call for every person who is banned from the club.

    @danielshamburger@danielshamburger2 ай бұрын
  • There should be a type hint for bob being a troublemaker

    @SusanAmberBruce@SusanAmberBruce2 ай бұрын
  • What is the name of the Font

    @PharmIT74@PharmIT742 ай бұрын
  • is filter not a good option in python?

    @noomade@noomade2 ай бұрын
    • it is pythonic to use comprehensions instead of map or filter

      @RM-xr8lq@RM-xr8lq2 ай бұрын
  • 2:45 scripts, which are meant to be run, do live in a bin-folder, don't end with .py but with no extension at all for unix or eg. .bat on windows and they do provide a documentation which is accessed by the command line options -h and --help. This again is a bad habit since it urges the users to search all .py files for such a section in order to find the scripts which can be run. And if they find them, they still don't know, whether the code is only for testing.

    @ThomasVWorm@ThomasVWorm2 ай бұрын
  • I think the most important python habit I have is to write as little code as possible in python, because python is a programming language by mathematicians and nowadays data scientist for themselves, and not actual software developers.

    @Sebastian-hg3xc@Sebastian-hg3xc29 күн бұрын
  • One of the great things about Python, is you can write code without a lot of boilerplate. I'm certainly not going to add boilerplate for someone else's idea of "clean code".

    @ytlongbeach@ytlongbeach2 ай бұрын
    • When you are making programs that are 1000+ lines of code, you'll realize how much simpler debugging would have been had you added type hinting / doc strings and breaking up functions into smaller ones. Granted his example of breaking up the code into separate functions was rather extreme, but he was just using it as an example. i don't necessarily agree with him on using type hinting when it's not part of the function parameters though.

      @resresres1@resresres12 ай бұрын
  • "So, here I'm going to type in long_names, and that's going to shadow the name above, but... Who cares for now? And, actually, apparently, MyPy cares a lot ^^`" Literally the best part of the video

    @hikaru-k-bit@hikaru-k-bitАй бұрын
KZhead