🐍"Python Tips for the Day" 👉 #1

1. Current version of Python is 3.8. [ As on 24/4/2020]

2. Python was created by Guido Van Rossum during December 1989, as a hobby project to keep him occupied in the week around Christmas.

3. Zen of a Python : Tim Peters wrote a poem called "Zen of Python" to highlight the philosophies of Python. One can get this poem by executing the folowing command  :  import this

4. The name of this language was derived from the British comedy series "Monty Python's Flying Circus"



[🐍PyTricks]: Python list slice syntax fun

Source :  Dan at Real Python info@realpython.com 
# Python's list slice syntax can be used without indices
# for a few fun and useful things:

# You can clear all elements from a list:
>>> lst = [1, 2, 3, 4, 5]
>>> del lst[:]
>>> lst
[]

# You can replace all elements of a list
# without creating a new list object:
>>> a = lst
>>> lst[:] = [7, 8, 9]
>>> lst
[7, 8, 9]
>>> a
[7, 8, 9]
>>> a is lst
True

# You can also create a (shallow) copy of a list:
>>> b = lst[:]
>>> b
[7, 8, 9]
>>> b is lst
False

[🐍PyTricks]: Python 3.5+ type annotations

Source : Dan at Real Python info@realpython.com

# Python 3.5+ supports 'type annotations' that can be
# used with tools like Mypy to write statically typed Python:

def my_add(a: int, b: int) -> int:
    return a + b

[🐍PyTricks]: Python's list comprehensions are awesome

Source :  Dan at Real Python info@realpython.com

# Python's list comprehensions are awesome.

vals = [expression 
        for value in collection 
        if condition]

# This is equivalent to:

vals = []
for value in collection:
    if condition:
        vals.append(expression)

# Example:

>>> even_squares = [x * x for x in range(10) if not x % 2]
>>> even_squares
[0, 4, 16, 36, 64]

[🐍PyTricks]: Python's built-in HTTP server

Source :  Dan at Real Python info@realpython.com 
# Python has a HTTP server built into the
# standard library. This is super handy for
# previewing websites.

# Python 3.x
$ python3 -m http.server

# Python 2.x
$ python -m SimpleHTTPServer 8000

# (This will serve the current directory at
#  http://localhost:8000)

Dicts can be used to emulate switch/case statements

Source :  Dan at Real Python info@realpython.com 

# Because Python has first-class functions they can
# be used to emulate switch/case statements

def dispatch_if(operator, x, y):
    if operator == 'add':
        return x + y
    elif operator == 'sub':
        return x - y
    elif operator == 'mul':
        return x * y
    elif operator == 'div':
        return x / y
    else:
        return None


def dispatch_dict(operator, x, y):
    return {
        'add': lambda: x + y,
        'sub': lambda: x - y,
        'mul': lambda: x * y,
        'div': lambda: x / y,
    }.get(operator, lambda: None)()


>>> dispatch_if('mul', 2, 8)
16

>>> dispatch_dict('mul', 2, 8)
16

>>> dispatch_if('unknown', 2, 8)
None

>>> dispatch_dict('unknown', 2, 8)
None

Functions are first-class citizens in Python

Source : Dan at Real Python info@realpython.com 

# Functions are first-class citizens in Python:

# They can be passed as arguments to other functions,
# returned as values from other functions, and
# assigned to variables and stored in data structures.

>>> def myfunc(a, b):
...     return a + b
...
>>> funcs = [myfunc]
>>> funcs[0]
<function myfunc at 0x107012230>
>>> funcs[0](2, 3)
5

"is" vs "=="

Source :  Dan at Real Python info@realpython.com 

# "is" vs "=="

>>> a = [1, 2, 3]
>>> b = a

>>> a is b
True
>>> a == b
True

>>> c = list(a)

>>> a == c
True
>>> a is c
False

# • "is" expressions evaluate to True if two 
#   variables point to the same object

# • "==" evaluates to True if the objects 
#   referred to by the variables are equal

Python's shorthand for in-place value swapping

Source : Dan at Real Python info@realpython.com

# Why Python Is Great:
# In-place value swapping

# Let's say we want to swap
# the values of a and b...
a = 23
b = 42

# The "classic" way to do it
# with a temporary variable:
tmp = a
a = b
b = tmp

# Python also lets us
# use this short-hand:
a, b = b, a

Measure the execution time of small bits of Python code with the "timeit" modul

Source :  Dan at Real Python info@realpython.com

# The "timeit" module lets you measure the execution
# time of small bits of Python code

>>> import timeit
>>> timeit.timeit('"-".join(str(n) for n in range(100))',
                  number=10000)

0.3412662749997253

>>> timeit.timeit('"-".join([str(n) for n in range(100)])',
                  number=10000)

0.2996307989997149

>>> timeit.timeit('"-".join(map(str, range(100)))',
                  number=10000)

0.24581470699922647

[🐍PyTricks]: You can use "json.dumps()" to pretty-print Python dicts

# The standard string repr for dicts is hard to read:
>>> my_mapping = {'a': 23, 'b': 42, 'c': 0xc0ffee}
>>> my_mapping
{'b': 42, 'c': 12648430. 'a': 23}  # 😞

# The "json" module can do a much better job:
>>> import json
>>> print(json.dumps(my_mapping, indent=4, sort_keys=True))
{
    "a": 23,
    "b": 42,
    "c": 12648430
}

# Note this only works with dicts containing
# primitive types (check out the "pprint" module):
>>> json.dumps({all: 'yup'})
TypeError: keys must be a string

[🐍PyTricks]: Function argument unpacking in Python

# Why Python Is Great:
# Function argument unpacking

def myfunc(x, y, z):
    print(x, y, z)

tuple_vec = (1, 0, 1)
dict_vec = {'x': 1, 'y': 0, 'z': 1}

>>> myfunc(*tuple_vec)
1, 0, 1

>>> myfunc(**dict_vec)
1, 0, 1

🐍PyTricks]: Merging two dicts in Python 3.5+ with a single expression

Source :

Dan at Real Python info@realpython.com


# How to merge two dictionaries
# in Python 3.5+

>>> x = {'a': 1, 'b': 2}
>>> y = {'b': 3, 'c': 4}

>>> z = {**x, **y}

>>> z
{'c': 4, 'a': 1, 'b': 3}

# In Python 2.x you could
# use this:
>>> z = dict(x, **y)
>>> z
{'a': 1, 'c': 4, 'b': 3}

# In these examples, Python merges dictionary keys
# in the order listed in the expression, overwriting 
# duplicates from left to right.
#
# See: https://www.youtube.com/watch?v=Duexw08KaC8

🐍PyTricks]: Different ways to test multiple flags at once in Python

Dan at Real Python info@realpython.com

🐍PyTricks]: How to sort a Python dict by value

Dan at Real Python info@realpython.com

🐍PyTricks]: The get() method on Python dicts and its "default" arg

# The get() method on dicts
# and its "default" argument

name_for_userid = {
    382: "Alice",
    590: "Bob",
    951: "Dilbert",
}

def greeting(userid):
    return "Hi %s!" % name_for_userid.get(userid, "there")

>>> greeting(382)
"Hi Alice!"

>>> greeting(333333)
"Hi there!"



Source :

Dan at Real Python info@realpython.com

[🐍PyTricks]: Python's namedtuples can be a great alternative to defining a class manually

# Why Python is Great: Namedtuples
# Using namedtuple is way shorter than
# defining a class manually:
>>> from collections import namedtuple
>>> Car = namedtuple('Car', 'color mileage')

# Our new "Car" class works as expected:
>>> my_car = Car('red', 3812.4)
>>> my_car.color
'red'
>>> my_car.mileage
3812.4

# We get a nice string repr for free:
>>> my_car
Car(color='red' , mileage=3812.4)

# Like tuples, namedtuples are immutable:
>>> my_car.color = 'blue'
AttributeError: "can't set attribute"


Dan at Real Python info@realpython.com

🐍PyTricks]: Try running "import this" inside a Python REPL ...

Source :

Dan at Real Python info@realpython.com

Python Weekly Issue 430

Source: rahul@pythonweekly.com

Python Weekly

Welcome to issue 430 of Python Weekly. I wish you all Happy New Year and I am excited to continue sending you the best Python related links in 2020.
From Our Sponsor 
 
Python developers are in demand on Vettery
Vettery is an online hiring marketplace that's changing the way people hire and get hired. Ready for a bold career move? Make a free profile, name your salary, and connect with hiring managers from top employers today.

Articles, Tutorials and Talks

Making Python Programs Blazingly Fast
Python haters always say, that one of reasons they don't want to use it, is that it's slow. Well, whether specific program - regardless of programming language used - is fast or slow is very much dependant on developer who wrote it and their skill and ability to write optimized and fast programs. So, let's prove some people wrong and let's see how we can improve performance of our Python programs and make them really fast!

Numba makes Python 1000x faster! 
In this video I introduce the absolute minimum you need to know about Numba which is a just in time compiler for a subset of Python and Numpy. The first half of the video is dedicated to a basic intro and to highlighting a number of very common mistakes people make when using Numba. The remaining video presents a real world-ish simulation problem, shows up to a 1000x acceleration with Numba in both single and multithreaded cases, and concludes with a "reading list" for learning more about Numba.

How to use Flask with gevent (uWSGI and Gunicorn editions)
Create asynchronous Flask application and run it with uWSGI or Gunicorn behind Nginx reverse proxy.

Introduction to ASGI: Emergence of an Async Python Web Ecosystem
There's a lot of exciting stuff happening in the Python web development ecosystem right now — one of the main drivers of this endeavour is ASGI, the Asynchronous Standard Gateway Interface. This post is targeted at people interested in recent trends of Python web development. It takes you on a guided tour about what ASGI is and what it means for modern Python web development.

Develop an Intuition for Severely Skewed Class Distributions
An imbalanced classification problem is a problem that involves predicting a class label where the distribution of class labels in the training dataset is not equal. Differences in the class distribution for an imbalanced classification problem will influence the choice of data preparation and modeling algorithms. Therefore it is critical that practitioners develop an intuition for the implications for different class distributions. In this tutorial, you will discover how to develop a practical intuition for imbalanced and highly skewed class distributions.

Robot development with Jupyter
This post shows the available tools in the Jupyter ecosystem to build advanced visualizations in Jupyter Notebooks and standalone web apps using Voilá, and how to deploy those apps to the robotics cloud.

Creating a Moon Animation Using NASA Images and Python
Here’s how we can create a video of the moon in just a few lines of python code!

Automating an Insider Selling Dashboard with Python & Tableau | Part 2: Collecting Live Stock Data 
In this part, we're using pandas datareader to collect real-time stock data for our insider trades dashboard. There are lots of good nuggets in here like using Pandas to calculate moving averages and to read html.

Python Dictionaries 101: A Detailed Visual Introduction

I'm not feeling the async pressure

Word raking with tf-idf and Python

Label smoothing with Keras, TensorFlow, and Deep Learning

Meditations on the Zen of Python

How to use Pandas get_dummies to Create Dummy Variables in Python


Interesting Projects, Tools and Libraries

Typer
Typer, build great CLIs. Easy to code. Based on Python type hints.

AI_Sudoku
GUI based Smart Sudoku Solver that tries to extract a sudoku puzzle from a photo and solve it.

klaxon
Mac OS notifications from Python.

django-simple-task
Simple background task for Django 3.

ffmpeg-python
Python bindings for FFmpeg - with complex filtering support.

Traffic-Signal-Violation-Detection-System
A Computer Vision based Traffic Signal Violation Detection System from video footage using YOLOv3 & Tkinter. (GUI Included)

pylightxl
A light weight, zero dependency, minial functionality excel read/writer python library.

XSS-Finder
Heavy-duty and Advanced Cross Site Scripting Scanner.

Robatim
Robatim is a pseudo-random music generator based on the conventions of the common practice period.


Upcoming Events and Webinars

Austin Python Meetup January 2020 - Austin, TX
Jupyter notebooks are excellent for exploration, particularly for analytics and visualization. However, when it comes to developing a library or self-contained code, we can find ourselves copying and pasting to our favorite text editor or IDE. In this presentation Leanne Fitzpatrick  will present nbdev, an elegant solution to this problem developed by fast.ai.

CI/CD for Python on AWS - Glen Allen, VA
We are going to be demonstrating 1) how to setup a Continuous Integration pipeline for a Python application and 2) how to implement Continuous Deployment using Python/Boto3 on AWS.

PyMNtos Python Presentation Night #80 - Minneapolis, MN

San Francisco Python Meetup January 2020 - San Francisco, CA

PyAtl Meetup January 2020 - Atlanta, GA
 
Our Other Newsletters
NoSQL Weekly - A free weekly newsletter featuring the best hand curated news, articles, tools and libraries, new releases, jobs etc related to NoSQL.

Founder Weekly - A free weekly newsletter for entrepreneurs featuring best curated content, must read articles, how to guides, tips and tricks, resources, events and more.