Tag Archives: Python

Creating a directory and its parents in Python

You can use the os.makedirs() function to create a new directory and any intermediate directories in its path that don’t exist:

import os
path = '/tmp/spam/eggs/ham'
if os.path.isdir(path):
    print 'Directory created'

The reverse operation of deleting a directory and all its subdirectories can be performed with shutil.rmtree():

import shutil

Modifying global variables in Python

You need to declare a global variable with global before you can modify it. Otherwise, you will just be creating a local variable with the same name.

x = 0

def main():
    print x # prints 0
    print x # prints 2

def f1(number):
    x = number

def f2(number):
    global x
    x = number

if __name__ == '__main__':

The yield keyword in Python

To understand how yield works, you need to understand iterables, iterators, and generators


An iterable is an object capable of returning its members one at a time. Iterables include:
All sequence types, such as:

  • list
  • str
  • tuple

Some none-sequence types, such as:

  • dict
  • file objects
  • any objects of user-defined classes with an __iter__() method or with a __getitem__() method that implements Sequence
    semantics (see below)

Iterables can be used in a for loop and in many other places where a sequence is needed:

  • zip()
  • map()

When an iterable object is passed to the built-in function iter(), it returns an iterator for the object.
The iterator is good for one pass over the set of values
It is usually not necessary to call iter() directly, as the for statement does this for you, creating a temporary unnamed
variable to hold the iterator for the duration of the loop.

User-defined iterables need to define one of __iter__() or __getitem__().

Called when an iterator is required for a container.
Iterator objects also need to implement this method; they are required to return themselves.

Called to implement self[key].
For sequence types, the accepted keys should be integers or slice objects.
The interpretation of negative slices is the responsibility of the __getitem__() method.
If key is of the wrong type, a TypeError may be raised.
If the key is of a value outside the set of indexes for the sequence, an IndexError should be raised.
For mapping types, if key is missing, a KeyError should be raised.


An iterator is an object representing a stream of data.
Calls to the object’s __next__() method (or passing it to the built-in function next()) return successive items in the
When no more data are available, a StopIteration exception is raised.
The iterator is then exhausted, and any subsequent calls to __next__() method will raise a StopIteration again.
Iterators are required to have an __iter__() method so every iterator is also iterable and may be used in most places where
other iterables are accepted.


The word generator refers to two things: a generator function and a generator iterator.

Generator function
A generator function is like a normal function except that it contains one or more yield expressions.
When a generator function is called, its code is not executed, and instead it returns a generator iterator.

Generator iterator
This is an iterator that controls the execution of the generator function in response to calls to the next() function.
Each yield in the associated generator function causes execution to be temporarily suspended. When the iterator resumes, execution continues from where it left off.