Problem in designing a global directory in python

F. Petitjean littlejohn.75 at news.free.fr
Tue Mar 29 13:20:27 EST 2005


Le 29 Mar 2005 09:50:46 -0800, Tian a écrit :
> I want to create a object directory called Context in my program, which
> is based on a dict to save and retrieve values/objects by string-type
> name. I have the definition like this:
> 
> utils.py
> --------------------
> global sysctx
# you are in the global scope of the utils module. This "global sysctx"
# has no meaning, replace by
sysctx = None  # create a global 'sysctx' name in utils namespace
> 
> class Context:
class Context(object):  # why not use "new-style" classes, we are in
2005
>     def __init__(self):
# I suppose that there is some __doc__ and code :-)
>     def set(self, name, obj, overwrite=True):
>     def get(self, name):
>     def has(self, name):
> 
> def init():
>     global sysctx
>     sysctx = Context()
> 
> def getContext():
>     global sysctx
>     return sysctx
> ---------------------
> 
> init() is called somewhere at the beginning of the program.
> In other modules, i want to use this in the following manner,
> 
>    from utils import *
Please do not use the from module import *  form
from utils import getContext
>    getContext().set(...)
You can also restrict the exported names of utils.py by adding a
__all__ = ('getContext',)
in utils.py.
> 
> but SOMETIMES I met following error located in "getContext()"
>          NameError: global name 'sysctx' is not defined
> 
> I found that when a module is in the same directory as utils.py, when I
> can simply use "utils" for importing, there is no such problem. But
> when i was writing a module in a deeper directory than utils.py, which
> has to use the full module name for importing, such as:
> 
>    from myproj.utils import *
>    getContext().set(...)
> 
> I got this error.
> 
> What should I do to correct that?
See above :-)  and post a follow-up to report if the issue is solved.
> 
PS sorry for bad english. I am not a native speaker.



More information about the Python-list mailing list