python

Constant variables in Python

Often Python is referred to as flexible and easy to learn programming language, mostly this is because it lacks some of the features you normally don't need that much. One of those features is const objects: being able to protect a variable against future change. Some languages call this "final", others "const", here is the best way I could think of to do this in Python:

import contextlib
@contextlib.contextmanager
def constant(vars):
    ''' Protect the return values of (callable) vars from change
   
    Use:
    def f():
        def constants():
            return a,b
        a=12
        b=24
        with constant(constants):
            print 'Do something'
            #If you would use b=2309 it will raise an exception after the with block.
    '''
    __protection_information = [(id(i), hash(i)) for i in vars()]
    yield
    for i, v in enumerate(vars()):
        pi = __protection_information[i]
        if not pi[0] == id(v):
            raise Exception('id() of const variable %i changed' % i)
        if not pi[1] == hash(v):
            raise Exception('hash() of const variable %i changed' % i)

Programming safely with Python

People often say that Python is an easy language, but like other easy languages it is often harder to make sure you are working in a safe manner. I'm not talking about security, but bug-free.

A) Assert allot:

assert something == True #This must be true because...
assert isinstance(variable, int) #This algorithm only makes sense with intergers

A nice Python typo to have

I had this typo in my code, and it gives you the weirdest errors ever:

translation = range(20)
translation = [[i, str('Number %i' % i)] for i in range(20)]
print 'Translations set: ',[i[1] for i in translation]

#Split the list, so we only take the upper part
firstN = 5
print 'First %i translations' % firstN, [i[1] or i in translation[:firstN]]

If you have not seen the typo yet, what would you expect the output to be? The output is...

Syndicate content