problem with global scope after package import via __init__.py
Mark Frazer
mark at somanetworks.com
Tue Aug 13 12:21:54 EDT 2002
Ok, I see now:
[mjfrazer at frogger pytest]$ python2
Python 2.2 (#1, Apr 12 2002, 15:29:57)
[GCC 2.96 20000731 (Red Hat Linux 7.2 2.96-109)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import p
>>> dir (p)
['__builtins__', '__doc__', '__file__', '__name__', '__path__', 'a', 'aval', 'get_a', 'set_a']
>>> type (p.a)
<type 'module'>
>>> dir (p.a)
['__builtins__', '__doc__', '__file__', '__name__', 'aval', 'get_a', 'set_a']
>>> type (p.aval)
<type 'int'>
>>> type (p.a.aval)
<type 'int'>
Denis S. Otkidach <ods at fep.ru> [02/08/13 11:59]:
> Make aval private (rename to _aval - it won't be imported with
> "from ... import *") and let users access it via {get|set}_a()
> functions only.
That's not what I wanted though. In order for my package users to access
scalars, I can move the scalar definitions into p/__init__.py and have the
package files import p itself.
[mjfrazer at frogger pytest]$ cat p/__init__.py
#__all__ = ['a']
aval = -999
from a import *
[mjfrazer at frogger pytest]$ cat p/a.py
#!/usr/bin/env python2
import p
def set_a (val):
p.aval = val
def get_a ():
return p.aval
if __name__ == "__main__":
val = 10
set_a (val)
assert get_a () == val
assert p.aval == val
[mjfrazer at frogger pytest]$ python2
Python 2.2 (#1, Apr 12 2002, 15:29:57)
[GCC 2.96 20000731 (Red Hat Linux 7.2 2.96-109)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import p
>>> dir (p)
['__builtins__', '__doc__', '__file__', '__name__', '__path__', 'a', 'aval', 'get_a', 'p', 'set_a']
>>> dir (p.a)
['__builtins__', '__doc__', '__file__', '__name__', 'get_a', 'p', 'set_a']
>>> p == p.a.p
1
Perhaps someone could add this to the FAQ?
Thanks for your help Denis.
-mark
--
I must be a robot. Why else would human women refuse to date me? - Fry
More information about the Python-list
mailing list