Decorator pattern in Python

Just found some interesting way of implementing Decorator design pattern in Python.

As Jason Smith said in his book (Elemental Design Patterns), “design patterns may be implemened in different ways in different programming languages”.

That’s said, design patterns are not some set of classes which will be implemented in a very similar way in different languages - they are just a way of doing something.

Thus, Decorator pattern is a way of wrapping some method’s or class’ behaviour. In Python it may be done with Context Managers:

from contextlib import contextmanager

@contextmanager
def tag(name):
    print "<%s>" % name,
    yield
    print "</%s>" % name,

with tag("h1"):
    print "moo",

print

with tag("div"):
    print "foo",

This code will end up wrapping print "foo" and print "moo" methods with printing some HTML tags around ‘em:

<h1>moo</h1>
<div>foo</div>

That is interesting as it implements Decorator design pattern in a bit hard-coded way, but using language features, not OOP ones.

Compare it to the “standard” OOP implementation in Python:

# -*-coding:utf-8 -*-
class SimpleText(object):
    def __init__(self, text):
        self.text = text

    def content(self):
        return self.text

    def __str__(self):
        return self.content()

class TagDecorator(SimpleText):
    def __init__(self, text, tag):
        super(TagDecorator, self).__init__(text)
        self.tag = tag

    def content(self):
        return '<{0}>{1}</{0}>'.format(self.tag, super(TagDecorator, self).content())

a = SimpleText('moo')
print('SimpleText: %s' % a)

b = TagDecorator('moo', 'h1')
print('TagDecorator (h1): %s' % b)

This one looks a bit… ugly… right? And though Python does not really care of which type are a and b, we may not need all this class hierarchy.

This is the might of context managers!

How to adjust widget’ size in Qt

Have you ever thought on how this:

could be turned to this:

without manually setting per-pixel sizes?

It’s simple as 1-2! Just take a look at the top of the UI editor and you’ll find a set of buttons, dedicated to do this adjustment for you:

Yet, there is just one small tip: first you should select a containing widget, whose children will be rearranged.

Like this:

Note the selected parent widget for vertical_layout.

Modelling in Blender

How did I came over from that to this…

NB: this is a 3D model potentially to be used in my ShootThem! game. Inspired by the Chicken Hat from Fable:

Chicken Hat from Fable

reworked materials for my rifle

Reworked materials for my rifle

Trying sculpting in Blender

Chicken body sculpt in Blender Chicken head in Blender

Have had some free time and tried sculpting in Blender 😜 With some other nice stuff 😁

creating some gun from a rough primitive model

Textured rifle made in Blender Rifle model with few material properties and a bit of sculpting

Creating some gun from a rough primitive model with some texture and sculpting. Yet, trying to get some pretty materials on this…

Having fun with Blender

Having fun texturing chicken head in Blender

Just some WIP. Having fun with Blender 😊

Installing deb package with dependencies

Oftenly,

sudo dpkg -i package_file.deb

fails with messages like dependency not satisfied.

To fix this, there are two ways:

  1. sudo dpkg -i package_file.deb && sudo apt-get -f install
  2. sudo dpkg -i --force-depends package_file.deb

Obviously, the second one is shorter =)

My very first model in Blender

Cup modelled in Blender Textured cup in Blender

Playing around with Blender - rendering, modifiers and some basic texturing and materials.

Rails tips

Found these on HabraHabr today. Here are some tricks I found usefull.

Private methods are not actually private

Let us have class:

class Moo
  private

  def self.foo
    puts 'foo'
  end
end

Here, class method foo is not private:

Foo.foo
=> 'foo'

Instance with params

Oftenly there is a need to create a class instance and set it some params (or, maybe, call some methods on it). It’s done usually like this:

moo = Moo.new
moo.foo = 'foo'
moo.bar

This can be shortened with the use of `tap` method:

moo = Moo.new.tap { |a| a.foo = 'foo'; a.bar }

Yet, it is more ruby-convenient and ruby-style to do it with the initialization block:

class Moo
  attr_accessor :foo

  def initialize(&block)
    yield self if block_given?
  end

  def bar
    puts "bar!"
  end
end

moo = Moo.new do |a|
  a.foo = 'foo'
  a.bar
end

puts moo.foo

Or even like this:

class Moo
  def initialize(&block)
    instance_eval &block if block_given?
  end

  def moo(val = nil)
    @moo = val unless val.nil?
    @moo
  end

  def bar
    puts "bar!"
  end
end

a = Moo.new do
  moo 'moo~!'
  bar
end

puts a.moo

Code-dependent migrations

When you have your migrations using your code, for example, like this:

class CreateDataVolumes < ActiveRecord::Migration
  def up
    Data::VOLUMES.times do |volume|
      create_table "data_#{volume}" do |t|
        # ...
      end
    end
  end
end

you then have a problem when updating your code. In our example, if you remove the constant Data::VOLUMES, you will have to either manually search for all the usages of this constant, or have a really intelliJent IDE ;)

Rather than using your existing code, stub it and copy-and-paste all migration-dependent code to the stubbing class:

class CreateDataVolumes < ActiveRecord::Migration
  class Data < AR::Base
    VOLUMES
  end

  def up
    Data::VOLUMES.times do |volume|
      # ...
    end
  end
end

Example with constant is rather stupid, whilst you may have some more critical code.