Git Product home page Git Product logo

fancy-python's Introduction

Fancy-python

This repo is based on my article How to be fancy with Python. It includes small Python tricks that will make your life much much easier. I hope they also help you become a better Python programmer. It is available as a jupyter notebook so you can clone and run it yourself. Also, if you know some tricks of your own, submit a pull request and I'll be more than happy to include it.

-1. Keyboard shortcuts

TAB to indent code

SHIFT + TAB to unindent code

To comment a bunch of code, select it and press CONTROL + /

To surround something with quotation marks or brackets around something, press SHIFT + " or SHIFT + (

0. Zip, enumerate

Usually in Python, we loop over things like this:

Comprehensions 1

To do the same with multiple lists, use zip

Comprehensions 2

And if you need indexes by any chance you can just do

Comprehensions 3

1. Comprehensions

Lists

The best part about Python is that you can accomplish so much in so less code. Take list comprehensions for example. If you want to create a list of numbers in a certain range you can easily do it as follows:

Comprehensions 4

You can also apply conditions on it very easily.

Comprehensions 5

One practical example of this is to convert a number to its digits.

Comprehensions_6

This concept of applying a function to every element of the list reminds me of map

Comprehensions_7

Just like lists, there are comprehensions for dictionaries and generators as well. We'll talk about generators later.

operator.itemgetter

Let's start with dictionaries. First let's learn about something called operator.itemgetter. It retreives every element of the specified index.

Say you have a list of lists like this

Dict_comp_1

and you want to get the first element of every inner list. You can do so as follows

Dict_comp_2

Cool right?

Let me give you one more example. You can use it with the key argument in the sorted function.

Dict_comp_3

See how it works?

Dictionaries

Okay back to dictionaries. A basic dictionary comprehension would be to map every element to an index.

Dict_comp_4

A good practice for such dictionaries is to also create the reverse mapping. Trust me, you'll need it later.

Dict_comp_5

We want to be able to do grouping in dictionaries like this:

Dict_comp_6

Let's break that down. The first thing we need to do for this to work is sorting by grade

Dict_comp_7

Then we can use itertools to group them

Dict_comp_8

And finally create a comprehension in the format we need by choosing just the 0th element from every tuple, in this case, student name

Dict_comp_9

Go over that one more time to make sure you understand it.

2. * operator

I bet those comprehensions were a lot to take in. Let's move onto lighter stuff for a while

The * operator can be used to repeat strings. For example

Star_1

Now you probably don’t want to print “Python is cool” a whole lot of times but you should use it for something like this

Star_2

The * operator can also be used to unpack iterables like lists

Star_3

We can also use it with function arguments when we don't know the number of arguments in advance

Star_4

*args is used for variable number of arguments and **kwargs is used for named arguments

3. Partials

Something else you can do with functions is create partial functions. What are they?

Suppose we have a function to calculate simple interest. We can set default values for some parameters (from right to left).

Partial_1

However, we cannot set the default value of just p in this way.

We can do so using a partial function. In a partial function, we set default values for some arguments, left to right and then use that as a function. Let’s set a default value for just p.

Partial_2

Although partials work from left to right, we can also skip parameters in between by using named arguments.

Partial_3

Partials are mainly used when you want to fix a few parameters and experiment with the rest.

4. Asserts

Test driven development means you write tests and then you write code to pass those tests. You can write mini-tests in Python using assert.

For example, you might want to make sure the shape of a certain object is what you expect it to be.

Assert_1

You can also write a custom error message after a comma. Writing these mini-tests will be super helpful in making sure parts of your code work as expected. It will also help you debug things efficiently.

5. Pathlib

If you haven't already stopped using strings for paths, stop right now!

pathlib_1

Check out this article for more examples and explanations.

6. Generators

We can use the yield keyword instead of return keyword in Python to create a generator. The advantage of using a generator is that is generates things on the fly and forgets them. This saves memory.

gen_1

We can also create them using comprehensions

gen_2

Proof that you can iterate over generators only once.

gen_3

To search for 5 in nums it had to generate numbers from 0 to 5. Now it starts from 6.

7. dir, isinstance and hasattr

If we want to know all the attributes and methods related to a particular object, we can use dir()

dir_1

We can also check for attributes directly using hasattr

dir_2

And we can check the type of a variable using isinstance. This is usually done to ensure the parameter passed to a function is of the correct type.

Conclusion

Those were some Python tricks that I believe would help everyone. Here's 2 more links for you. Keep learning.

How to be fancy with OOP in Python

Some neat Jupyter tricks.

fancy-python's People

Contributors

dipam7 avatar

Stargazers

Hadj H. avatar

Watchers

James Cloos avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.