[Python编程(第4版)].(Programming.Python.4th.Edition).Mark.Lutz.文字版

(yzsuai) #1

Here is an example of the problem this module addresses (but you have to pretend that
some of these calls are made by linked-in C code, not by Python; I changed USER in
the shell prior to this session with an export command):


.../PP4E/Integrate/Extend/Cenviron$ python
>>> import os
>>> os.environ['USER'] # initialized from the shell
'skipper'
>>> from cenviron import getenv, putenv # direct C library call access
>>> getenv('USER')
'skipper'
>>> putenv('USER', 'gilligan') # changes for C but not Python
>>> getenv('USER')
'gilligan'
>>> os.environ['USER'] # oops--does not fetch values again
'skipper'
>>> os.getenv('USER') # ditto
'skipper'

Adding Wrapper Classes to Flat Libraries


As is, the C extension module exports a function-based interface, but it’s easy to wrap
its functions in Python code that makes the interface look any way you like. For in-
stance, Example 20-10 makes the functions accessible by dictionary indexing and in-
tegrates with the os.environ object—it guarantees that the object will stay in sync with
fetches and changes made by calling our C extension functions.


Example 20-10. PP4E\Integrate\Extend\Cenviron\envmap.py


import os
from cenviron import getenv, putenv # get C module's methods


class EnvMapping: # wrap in a Python class
def setitem(self, key, value):
os.environ[key] = value # on writes: Env[key]=value
putenv(key, value) # put in os.environ too


def getitem(self, key):
value = getenv(key) # on reads: Env[key]
os.environ[key] = value # integrity check
return value


Env = EnvMapping() # make one instance


To use this module, clients may import its Env object using Env['var'] dictionary syntax
to refer to environment variables. Example 20-11 goes a step further and exports the
functions as qualified attribute names rather than as calls or keys—variables are refer-
enced with Env.var attribute syntax.


Wrapping C Environment Calls | 1499
Free download pdf