Hacker News new | ask | show | jobs
by yes_or_gnome 3217 days ago
Your Point3D class is _not_ functionally equivalent to a NamedTuple. The class is so minimal that I wouldn't bother calling it a class as much as I would call it a glorified dictionary.

I do like the concept of Structs. I first used them in Ruby, so I figured that all "very high" languages had the concept. Python, however "struct" has a very different meaning in Python. sigh It's intended for encoding/decoding binary data from strings/bytes.

https://docs.python.org/3.6/library/struct.html

There is a lesser known use case for the type(...) function. Normally, one would use it to find out an object's type.

     >>> type(42)
     <type 'int'>
     >>> type("foo")
     <type 'str'>
     >>> type(type)
     <type 'type'>
But, it can also be used to create new class types. https://docs.python.org/3.6/library/functions.html#type

     >>> Point3D = type("Point3D", (object,), dict(x=0,y=0,z=0))
     >>> my_point = Point3D()
     >>> my_point.x
     0
     >>> my_point.y = 42
     >>> my_point.y
     42
     >>> my_point.a
     Traceback (most recent call last):
       File "<stdin>", line 1, in <module>
     AttributeError: 'Point3D' object has no attribute 'a'
Which is, essentially, what Ruby's Struct class provides. And, Python objects don't have privacy, so it's more comparable to the OpenStruct class.

Edit: Just wanted to tack on a shout out to Attrs which is really nice improvement to "Struct" concept. http://www.attrs.org/en/stable/ h/t hynek

2 comments

>Python, however "struct" has a very different meaning in Python. sigh It's intended for encoding/decoding binary data from strings/bytes.

That's because the struct module is for dealing with structs, in the C/C++ sense. Like actual structs.

That aside, attrs is a great library!