[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]

Re: [pygame] @



This is getting off topic for a game oriented mailing list, but many of the things other languages use macro to accomplish come naturally to Python because it is dynamically typed. For instance the function:

def do_add(x, y):
   return x + y

will work with integers, floats, complex numbers, lists and any other class that defines an addition operation. Python has many hooks that take callback functions. These can redefine the way imports work, for instance. Also, metaclasses allow one to change how class declarations work. So though there is no mechanism to add new syntax and constructs to the Python language, there are plenty of ways to change how the existing syntax works.

Lenard


Noah Kantrowitz wrote:

Python has no such system. Boo is a python-like language that supports hygienic macros.

--Noah

On Dec 31, 2008, at 1:20 PM, Lin Parkh wrote:

While we're on this kind of topic what is the best approach in python to creating code macros? That is ability to write a higher level language (or script) which translates down into python? Decorators look like they would be part of that story. Is that the best way or is their a more general way?
Thanks,
 Lin
p.s. I used to write code macros in LISP... context I am coming from.
----- Original Message ----- From: "Michael George" <mdgeorge@xxxxxxxxxxxxxx>
To: <pygame-users@xxxxxxxx>
Sent: Wednesday, December 31, 2008 9:56 AM
Subject: Re: [pygame] @


Michael Phipps wrote:
Yanom -
A decorator is a method that takes another method as a parameter so that it can do something. It is usually used for aspect oriented programming.

For example:

def logThisMethodCall(methodCall)
   # Do some logging here

@logThisMethodCall
def myMethod(a,b,c)
   # do Somthing in here

Now, whenever you call "myMethod", logThisMethodCall gets called first, with the invocation of myMethod passed into it. You can use it for logging, security (i.e. does this person have permission to be calling this), etc.

Michael



This isn't quite right. logThisMethodCall doesn't get called when you call myMethod, but when you _define_ myMethod. So to fix this example:

def logThisMethodCall(methodCall):
  def result(a,b,c):
      # do some logging here
      methodCall(a,b,c)
  return result

@logThisMethodCall
def myMethod(a,b,c):
  # do something here

When you define myMethod, logThisMethodCall is called to create a replacement function for myMethod. it returns a new function "result" which gets called instead of the original myMethod whenever someone calls myMethod. result does some logging and then calls the orginal myMethod.



--
Lenard Lindstrom
<len-l@xxxxxxxxx>