Search code examples
pythonsyntaxsemantics

Understanding python syntax - variable followed by parenthesis


I saw this syntax in the python implementation of bitcoin over here.

https://github.com/samrushing/caesure/blob/master/caesure/bitcoin.py

I have never seen this syntax before, can someone explain it to me or show me somewhere in the documentation where I can understand it?

    def dump (self, fout=sys.stdout):
        D = fout.write
        D ('hash: %s\n' % (hexify (dhash (self.render())),))
        D ('inputs: %d\n' % (len(self.inputs)))
        for i in range (len (self.inputs)):
            (outpoint, index), script, sequence = self.inputs[i]
            try:
                redeem = pprint_script (parse_script (script))
            except ScriptError:
                redeem = script.encode ('hex')
            D ('%3d %064x:%d %r %d\n' % (i, outpoint, index, redeem, sequence))
        D ('outputs: %d\n' % (len(self.outputs),))
        for i in range (len (self.outputs)):
            value, pk_script = self.outputs[i]
            pk_script = pprint_script (parse_script (pk_script))
            D ('%3d %s %r\n' % (i, bcrepr (value), pk_script))
        D ('lock_time: %s\n' % (self.lock_time,))

I'm talking about D ('hash: %s\n' % (hexify (dhash (self.render())),))

There are many lines where there is a variable followed by a parenthesis. I don't understand what it does.


Solution

  • In Python you can assign functions to variables.

    fout.write is a function, so in this example, D is assigned to that function.

    D = fout.write

    In this line D ('hash: %s\n' % (hexify (dhash (self.render())),)), you are calling the function D, that is, fout.write. It would be the same as:

    fout.write('hash: %s\n' % (hexify (dhash (self.render())),))