Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #101369 > unrolled thread
| Started by | Joseph Fox-Rabinovitz <jfoxrabinovitz@gmail.com> |
|---|---|
| First post | 2016-01-07 12:33 -0500 |
| Last post | 2016-01-07 12:33 -0500 |
| Articles | 1 — 1 participant |
Back to article view | Back to comp.lang.python
This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by
below is the oldest one visible, not the original post.
Re: Unable to access module attribute with underscores in class method, Python 3 Joseph Fox-Rabinovitz <jfoxrabinovitz@gmail.com> - 2016-01-07 12:33 -0500
| From | Joseph Fox-Rabinovitz <jfoxrabinovitz@gmail.com> |
|---|---|
| Date | 2016-01-07 12:33 -0500 |
| Subject | Re: Unable to access module attribute with underscores in class method, Python 3 |
| Message-ID | <mailman.63.1452258624.2305.python-list@python.org> |
> On Thu, Jan 7, 2016 at 11:14 AM, Joseph Fox-Rabinovitz <jfoxrabinovitz@gmail.com> wrote:
>
> Hi,
>
> I have a module attribute whose name starts with a pair of underscores. I am apparently unable to access it directly in a class method (within the same module, but that is not relevant as far as I can tell). The following bit of code illustrates the situation:
>
> __a = 3
> class B:
> def __init__(self):
> global __a
> self.a = __a
> b = B()
>
> This results in a NameError because of name-mangling, despite the global declaration:
>
> Traceback (most recent call last):
> File "<stdin>", line 1, in <module>
> File "<stdin>", line 4, in __init__
> NameError: name '_B__a' is not defined
>
> Not using global does not make a difference. I posted a similar question on Stack Overflow, where the only reasonable answer given was to wrap __a in a container whose name is not mangled. For example, doing `self.a = globals()['__a']` or manually creating a dictionary with a non-mangled name and accessing that.
>
> I feel that there should be some way of accessing __a within the class directly in Python 3. Clearly my expectation that global would fix the issue is incorrect. I would appreciate either a solution or an explanation of what is going on that would convince me that accessing a module attribute in such a way should be forbidden.
>
> -Joseph Fox-Rabinovitz
>
> P.S. For reference, the Stack Overflow question is here: http://stackoverflow.com/questions/34621484/how-to-access-private-variable-of-python-module-from-class
One more detail that makes me think that name mangling may be getting
greedy to the point of bugginess:
__a = 3
class B:
def __init__(self):
m = sys.modules[__name__]
self.a = m.__a
b = B()
Raises the same exception as all the other way I tried to access __a:
'module' object has no attribute '_B__a'!
-Joseph
Back to top | Article view | comp.lang.python
csiph-web