TE
TechEcho
Home24h TopNewestBestAskShowJobs
GitHubTwitter
Home

TechEcho

A tech news platform built with Next.js, providing global tech news and discussions.

GitHubTwitter

Home

HomeNewestBestAskShowJobs

Resources

HackerNews APIOriginal HackerNewsNext.js

© 2025 TechEcho. All rights reserved.

Dynamically create a type with Python

51 pointsby henryprecheuralmost 16 years ago

2 comments

daekenalmost 16 years ago
Good little introduction in terms of general use, but I think a solid example is in order, as it's a very useful technique.<p>A while back, I created a Struct class, which allows the creation of C-like structs, but you had to create a subclass of Struct, specify the endianness as a class attribute, and create a __format__ method that built the struct members. A little while ago, I had the thought to wrap it into a decorator, defStruct/defStructLE/defStructBE, that automagickly calls 'type' to build the appropriate Struct class for you, given a method.<p>So what once was:<p><pre><code> class Foo(Struct): __endian__ = Struct.LE def __format__(self): self.foo = Struct.uint32 self.bar = Struct.string(self.foo) </code></pre> Became:<p><pre><code> @defStructLE def Foo(self): self.foo = Struct.uint32 self.bar = Struct.string(self.foo) </code></pre> Much, much cleaner, all thanks to the magic of 'type'.
评论 #662205 未加载
mortenofflinealmost 16 years ago
If he wanted to persist the classes offered by the server you could actually write the python code to a module, reload module and import the class proper. Did that a while ago so I didn't have to restart a daemon all the time.