Archive | python RSS feed for this section

Fixing and avoiding memory leaks in Python

12 Apr

Reference counting

Python uses reference counting for its memory management. This means that it keeps count of how many references your script still has to an object, and when that count becomes zero, the object is deleted.

a = "text"
b = a
a = None
b = None

The string object containing “text” is deleted after the last reference, in this case b, is set to None (or any other value).

The problem of circular references

A problem arises when one object holds a reference to another which has a reference back to the first, either directly or in a chain. This is not so hypothetical, as it often happens in hierarchical or cyclic graph structures. In the following tree structure for example, parent nodes hold references to child nodes, while the child nodes hold references to their parent. Continue reading

Advertisements

Embedding Python, Ruby and Lua compared (part 1)

26 Mar

This is a series of comparisons between the scripting languages I personally have used as an embedded language in a C/C++ program. All have their use depending on the situation. For a game or mobile application for example, Lua is preferred as it is small and fast. It also is best when multiple interpreters are needed. Python and Ruby have a more concise syntax and have more libraries to work with in case that is needed. Their object system is also easier to grasp than the table system used in Lua. In this part I will just concentrate on exporting methods from C to the scripting languages. In a later part I will compare the object systems. Continue reading

Using decorators and closures in python

11 Mar

Decorators

A decorator wraps a class or method to extend it. In python the syntax used to wrap the original function is @decoratorname. For example let’s say the original function A needs to be decorated with B:
def B(a):
  def C(*args):
    return 2 * a(*args);
  return C

@B
def A(x, y):
  return x + y;

print A(2, 3)

Continue reading

Fixing Sublime Text 2 for a Japanese Windows system

8 Feb

Sublime Text 2 is a programmer’s text editor with build-in Python scripting. Usually I use Programmer’s Notepad as a lightweight text editor, but I decided to give Sublime a try.

Continue reading

Modifying python classes at run-time

1 Feb

Adding methods to python objects and classes at run-time can be very handy when API specifications are fluid or when loading custom file formats. Think for example of an object implementing a protocol defined as XML or another descriptive language. Or an object giving access to stored database methods. Instead of only having a general execute method or having to recreate a static API file, all the described methods can be added to a class at runtime.

Continue reading