Python Forum

Full Version: __dict__ in math library
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
hi
i saw that there is no "__dict__" in math library. namely:
import math
"__dict__ " in dir(math)
the result will be False. but when i write
math.__dict__.items() 
, a large dict_items object will be shown in idle.
how is it possible when there is not __dict__ in math lib,then there is math.__dict__.items() ?
thanks
https://docs.python.org/3/library/stdtyp...attributes

Quote:Special Attributes

The implementation adds a few special read-only attributes to several object types, where they are relevant. Some of these are not reported by the dir() built-in function.

object.__dict__


A dictionary or other mapping object used to store an object’s (writable) attributes.
hi
as i said before, the
math.__dict__.items()
gives a dict_items object with first element( as i run) :
('__names__','math') .
how can I get this element? how can I get '__names__' ? and how for 'math'?
thanks
Get attribute values the same way as any other object.
import math

print(math.__name__)
print(getattr(math, "__name__"))
You should not be using __dict__ directly. Not all objects have __dict__. Some have __slots__, but dir() works for both.
class Base:
    __slots__ = "foo", "bar"


class Right(Base):
    __slots__ = ("baz",)


r = Right()
print(dir(r))
print(r.__dict__)
Error:
Traceback (most recent call last): File "...", line 11, in <module> print(r.__dict__) AttributeError: 'Right' object has no attribute '__dict__'. Did you mean: '__dir__'?
hi deanhystad
is there a way to print all elements in math.__dict__.names()? namely as:
('__names__','math')
( .......)
(...)
.
.
.

how?
hi
excuse me for more questions
math.__dict__.names() is of type dict_items type. what is the difference between 'dict_items' type and the 'dict' type?
in page https://realpython.com/python-eval-funct...with-input there is a code( large code, so i not import here) that contains the below line:
ALLOWED_NAMES = {
    k: v for k, v in math.__dict__.items() if not k.startswith("__")
}
so if I write:
for k, v in math.__dict__.items():
      print(k,v)
it prints something.
but for a dictionary as :
dic={'x': 1, 'y': 2, 'z': 3, 'w': 4}
then :
for a,b in dic:
    print(a,b)
then idle creates an error:
Error:
Traceback (most recent call last): File "<pyshell#39>", line 1, in <module> for a,b in dic: ValueError: not enough values to unpack (expected 2, got 1)
what is the difference between them? thanks for more explain.
when you iterate over dict, you iterate over keys only, i.e. for key in some_dict: is equivalent to for key in some_dict.keys():. You need to iterate over some_dict.items() if you want to get both key and value, i.e. you get (key, value) tuple which you unpack, in your case into a and b respectively