[Python-ideas] Are we supposed to be able to have our own class dictionary in python 3?

Joy Diamond python.gem at gmail.com
Sat Nov 3 16:54:39 EDT 2018


Team,

Are we supposed to be able to have our own class dictionary in python 3?

If we currently cannot -- do we want to be able to?

That we can have out own class dictionary in python 3 is strongly implied
in the following at https://www.python.org/dev/peps/pep-3115/ where it says:

"""

    # The metaclass invocation
    def __new__(cls, name, bases, classdict):
        # Note that we replace the classdict with a regular
        # dict before passing it to the superclass, so that we
        # don't continue to record member names after the class
        # has been created.
        result = type.__new__(cls, name, bases, dict(classdict))
        result.member_names = classdict.member_names
        return result

"""

I don't understand this.  As far as I can tell, no matter what class
dictionary you pass into `type.__new__` it creates a copy of it.

Am I missing something?  Is this supposed to work?  Is the documentation
wrong?

Thanks,

Joy Diamond.

Program that shows that the class dictionary created is not what we pass in
--- Shows the actual symbol table is `dict` not `SymbolTable`

class SymbolTable(dict):
    pass

members = SymbolTable(a = 1)

X = type('X', ((object,)), members)

members['b'] = 2

print('X.a: {}'.format(X.a))

try:
    print('X.b: {}'.format(X.b))
except AttributeError as e:
    print('X.b: does not exist')

#
#   Get the actual symbol table of `X`, bypassing the mapping proxy.
#
X__symbol_table = __import__('gc').get_referents(X.__dict__)[0]

print('The type of the actual symbol table of X is: {} with keys:
{}'.format(
      type(X__symbol_table),
      X__symbol_table.keys()))


# Prints out
# X.a: 1
# X.b: does not exist
# The type of the actual symbol table of X is: <class 'dict'> with keys:
dict_keys(['a', '__module__', '__dict__', '__weakref__', '__doc__'])

<https://www.avast.com/sig-email?utm_medium=email&utm_source=link&utm_campaign=sig-email&utm_content=webmail&utm_term=icon>
Virus-free.
www.avast.com
<https://www.avast.com/sig-email?utm_medium=email&utm_source=link&utm_campaign=sig-email&utm_content=webmail&utm_term=link>
<#DAB4FAD8-2DD7-40BB-A1B8-4E2AA1F9FDF2>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20181103/a5d969a7/attachment.html>


More information about the Python-ideas mailing list