Macros in Python?
Jp Calderone
exarkun at intarweb.us
Wed Apr 9 18:56:39 EDT 2003
On Wed, Apr 09, 2003 at 08:58:04PM +0200, Dominic wrote:
>
>
> (defmacro with-root-privs (() &body body)
> (let ((oldidsym (gensym)))
> `(let ((,oldidsym (geteuid)))
> (seteuid 0)
> (unwind-protect
> (progn , at body)
> (seteuid ,oldidsym)))))
>
> Is there an easy way to produce similar code
> in Python which gurantees that certain things
> happen around some code? (Maybe by using
> generators?)
Yay metaclasses yay!
class WrapperMetaclass:
def __init__(self, prefix, wrapper):
self.prefix = prefix
self.wrapper = wrapper
def __call__(self, name, bases, attrs):
for k in attrs:
if k.startswith(self.prefix):
attrs[k] = self.wrapper(attrs[k])
return type(name, bases, attrs)
> [snip]
>
> Is something like this feasible?
>
> def server(a,b):
> if cond:
> ...
> else:
> With_Root_Privs:
> if x in user:
> active.append(x)
> (...)
>
def acquireRoot():
# Whatever
def releaseRoot():
# Whatever
def superuserWrapper(f):
def function(*args, **kw):
acquireRoot()
try:
f(*args, **kw)
finally:
releaseRoot()
return function
class Server(object):
__metaclass__ = WrapperMetaclass('asroot_', superuserWrapper)
def asroot_addUser(self, x):
active.append(x)
def checkCondition(self, a, b):
if cond:
....
else:
self.asroot_addUser(x)
Jp
> --
> http://mail.python.org/mailman/listinfo/python-list
--
Lowery's Law:
If it jams -- force it. If it breaks, it needed replacing anyway.
--
up 20 days, 19:01, 1 user, load average: 0.21, 0.15, 0.05
More information about the Python-list
mailing list