MCPcopy Create free account
hub / github.com/ipython/ipython / __setattr__

Method __setattr__

IPython/utils/ipstruct.py:90–123  ·  view source on GitHub ↗

Set an attr with protection of class members. This calls :meth:`self.__setitem__` but convert :exc:`KeyError` to :exc:`AttributeError`. Examples -------- >>> s = Struct() >>> s.a = 10 >>> s.a 10 >>> try: ... s.get

(self, key, value)

Source from the content-addressed store, hash-verified

88 dict.__setitem__(self, key, value)
89
90 def __setattr__(self, key, value):
91 """Set an attr with protection of class members.
92
93 This calls :meth:`self.__setitem__` but convert :exc:`KeyError` to
94 :exc:`AttributeError`.
95
96 Examples
97 --------
98
99 >>> s = Struct()
100 >>> s.a = 10
101 >>> s.a
102 10
103 >>> try:
104 ... s.get = 10
105 ... except AttributeError:
106 ... print("you can't set a class member")
107 ...
108 you can't set a class member
109 """
110 # If key is an str it might be a class member or instance var
111 if isinstance(key, str):
112 # I can't simply call hasattr here because it calls getattr, which
113 # calls self.__getattr__, which returns True for keys in
114 # self._data. But I only want keys in the class and in
115 # self.__dict__
116 if key in self.__dict__ or hasattr(Struct, key):
117 raise AttributeError(
118 'attr %s is a protected member of class Struct.' % key
119 )
120 try:
121 self.__setitem__(key, value)
122 except KeyError as e:
123 raise AttributeError(e)
124
125 def __getattr__(self, key):
126 """Get an attr by calling :meth:`dict.__getitem__`.

Callers 3

__init__Method · 0.45
allow_new_attrMethod · 0.45
__init__Method · 0.45

Calls 1

__setitem__Method · 0.95

Tested by

no test coverage detected