[Python-Dev] Accessing globals without dict lookup (original) (raw)

Guido van Rossum guido@python.org
Fri, 08 Feb 2002 11:50:31 -0500


Inspired by talks by Jeremy and Skip on DevDay, here's a different idea for speeding up access to globals. It retain semantics but (like Jeremy's proposal) changes the type of a module's dict.

I believe that's it. I think this faithfully implements the current semantics (where a global can shadow a builtin), but without the need for any dict lookups when accessing globals, except in cases where an explicit dict is passed to exec or eval().

Compare this to Jeremy's scheme using dlicts:

http://www.zope.org/Members/jeremy/CurrentAndFutureProjects/FastGlobals

Here's a implementation sketch for cell and celldict. Note in particular that keys() only returns the keys for which the cell's objptr is not NULL.

NULL = object() # used as a token

class cell(object):

def __init__(self):
    self.objptr = NULL
    self.cellptr = NULL

class celldict(object):

def __init__(self):
    self.__dict = {} # dict of cells

def getcell(self, key):
    c = self.__dict.get(key)
    if c is None:
        c = cell()
        self.__dict[key] = c
    return c

def __getitem__(self, key):
    c = self.__dict.get(key)
    if c is None:
        raise KeyError, key
    value = c.objptr
    if value is NULL:
        raise KeyError, key
    else:
        return value

def __setitem__(self, key, value):
    c = self.__dict.get(key)
    if c is None:
        c = cell()
        self.__dict[key] = c
    c.objptr = value

def __delitem__(self, key):
    c = self.__dict.get(key)
    if c is None or c.objptr is NULL:
        raise KeyError, key
    c.objptr = NULL

def keys(self):
    return [c.objptr for c in self.__dict.keys() if c.objptr is not NULL]

def clear(self):
    for c in self.__dict.values():
        c.objptr = NULL

# Etc.

--Guido van Rossum (home page: http://www.python.org/~guido/)