🐍PyTricks: Dicts can be used to emulate switch/case statements

Fonte: RealPython


# 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

[🐍PyTricks]: "is" vs "=="

Original: Python Tricks Book


# "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

[!NOTE] Information the user should notice even if skimming.

Se você gostou dessa dica, você vai adorar este livro: Python Tricks: The Book

Instalando Pandas e (virtualenv) no c9

Para instalar um ambiente virtual  para programação em Python 3 no c9, criei 2 scripts:

  • install-01.sh
  • install-02.sh:

install-01.sh:


#! /bin/bash

#Baixando Miniconda 64Bits para Linux
wget https://repo.continuum.io/miniconda/Miniconda3-latest-Linux-x86_64.sh

#Mudando permissões para execução
chmod a+x Miniconda3-latest-Linux-x86_64.sh

#Executando 
./Miniconda3-latest-Linux-x86_64.sh

# Aceite tudo que pedir

# Feche o terminal e abra novamente.
echo 'execute o install02.sh'

install-02.sh:


#! /bin/bash

# Criando um ambiente (sand box instance)
conda create -n py3 python=3 ipython

# Ativando o ambiente criado
source activate py3

# Instalar o Gerenciador de pacotes pip
conda install pip

# Na instalacao instale os pacotes
#pip install numpy
#pip install pandas
#pip install matplotlib

# qual ipython vai ser usado no ambiente? pip freeze mostra
pip freeze

# Instalando ipython notebook
conda install ipython-notebook

# Installing the packages
conda install numpy
conda install pandas
conda install matplotlib

I have installed more than only pandas, as you can see in the script you can install any package using conda install package_name