Running tests using the Contexts python library in Pycharm

Using:

1) Create a new External Tool

In Pycharm, go to: Settings/Tools/External Tools

Create a new Tool:

  • "Name": give a distinct name
  • "Program": give the path of where run-contexts is in the path where the python interpreter is located for the project (typically a virtual environment)
  • "Arguments": click on "Insert Macro" for this field and select "SelectedText"
  • "Working directory": Where the python project is

2) Create a new Keymap

In Pycharm, go to: Settings/Keymap

Search for the "Name" you have defined in 1), select the "External Tool" that you have just created and double click to "Add Keyboard Shortcut", eg "Alt+r"

3) Run tests

Now you can run the tests that you are currently on by pressing the Keymap you have defined in 2), eg "Alt+r" here

String in python2 vs python3

Difference between basestring and str in python

In Python versions prior to 3.0 there are two kinds of strings "plain strings" and "unicode strings". Plain strings (str) cannot represent characters outside of the Latin alphabet (ignoring details of code pages for simplicity). Unicode strings (unicode) can represent characters from any alphabet including some fictional ones like Klingon.

So why have two kinds of strings, would it not be better to just have Unicode since that would cover all the cases? Well it is better to have only Unicode but Python was created before Unicode was the preferred method for representing strings. It takes time to transition the string type in a language with many users, in Python 3.0 it is finally the case that all strings are Unicode.

The inheritance hierarchy of Python strings pre-3.0 is:

 object
    |
    |
basestring
   / \
  /   \
str  unicode

'basestring' introduced in Python 2.3 can be thought of as a step in the direction of string unification as it can be used to check whether an object is an instance of str or unicode

>>> string1 = "I am a plain string"
>>> string2 = u"I am a unicode string"
>>> isinstance(string1, str)
True
>>> isinstance(string2, str)
False
>>> isinstance(string1, unicode)
False
>>> isinstance(string2, unicode)
True
>>> isinstance(string1, basestring)
True
>>> isinstance(string2, basestring)
True

Source: https://stackoverflow.com/questions/1979004/what-is-the-difference-between-isinstanceaaa-basestring-and-isinstanceaaa

defaultdict of defaultdict, nested

Creating arbitrary level of nested dictionaries using defaultdict:

from collections import defaultdict

def recursive_defaultdict():
    return defaultdict(recursive_defaultdict)
>>> x = recursive_defaultdict()
>>> x['a']['b']['c']['d']
defaultdict(<function recursive_defaultdict at 0x7fbf9b0496e0>, {})
>>> import json
>>> print json.dumps(x)
{"a": {"b": {"c": {"d": {}}}}}

With a lambda:

recursive_defaultdict = lambda: defaultdict(rec_dd)

Source: https://stackoverflow.com/questions/19189274/defaultdict-of-defaultdict-nested

Python and Google spreadsheet

Skype with Python

Create the virtualenv

virtualenv skype_venv -p /usr/bin/python2.7 --system-site-packages

Note that I am specyfying the python2 interpreter, and using the system site packages (the python libraries already installed).

Install the Skype4Py library

You can install it with pip.

source skype_venv/bin/activate
pip install Skype4Py

Note that this library allows us to control Skype client application. It means that you will need to have a skype client installed with which you will interact using python.

Source: https://pypi.python.org/pypi/Skype4Py/

Use the library

Open your skype client and launch a python prompt

>>> import Skype4Py
>>> skype = Skype4Py.Skype()
>>> skype.Attach()

At this point, the Skype client will ask for authorization:

Skype4Py authorisation

And now, you can for example get the list of all your contacts:

>>> print 'Your full name:', skype.CurrentUser.FullName
>>> print 'Your contacts:'
>>> for user in skype.Friends:
        print '    ', user.FullName

To go further:

https://leakforums.net/thread-641974?tid=641974&&tid=641974&&pq=2

https://sinister.ly/Thread-Tutorial-Create-your-own-SkypeBOT

https://media.readthedocs.org/pdf/sevabot-skype-bot/latest/sevabot-skype-bot.pdf

How to get the first/last day of the previous month?

How to get first/last day of the previous month?

>>> from datetime import date
>>> from dateutil.relativedelta import relativedelta
>>> today = date.today()
>>> d = today - relativedelta(months=1)
>>> date(d.year, d.month, 1)
datetime.date(2008, 12, 1)
>>> date(today.year, today.month, 1) - relativedelta(days=1)
datetime.date(2008, 12, 31)
>>>

Abstraction in python

Abstraction in python

For example, when copying files:

import shutil
shutil.copy('file.txt', 'copy.txt')

It is much more abstract (and simpler) to use the shutil library than:

with open(src, 'rb') as fsrc:
    with open(dst, 'wb') as fdst:
        while True:
            buf = fsrc.read(buf_size)
            if not buf:
                break
            fdst.write(buf)

Sorting a list with two criteria in python

We want to sort a list of elements with the first element in ascending order and the second element in descending order.

Using the lambda function:

occurences = {'bat': 2, 'mat': 1, 'cat': 3}
sorted(occurences.items(), key=lambda x: (-x[1], x[0]))

The -x[1] is for the reversed sort.

By order of priority, we first sort with the 2nd element (x[1]), then with the 1st element (x[0])

Example for an interview question: