How would I write this C code in Python?

Bruno Desthuilliers bruno.42.desthuilliers at wtf.websiteburo.oops.com
Tue Jul 10 13:05:32 CEST 2007


Marc 'BlackJack' Rintsch a écrit :
> On Fri, 06 Jul 2007 17:31:50 +0000, DeveloperX wrote:
> 
>> I am trying to figure out how to rewrite the following chunk of code
>> in Python:
>>
>> C source
>> [code]
>> typedef struct PF
>> {
>>   int flags;
>>   long user;
>>   char*filename;
>>   unsigned char buffer[MAXBUFFERSIZE];
>> } PF;
>>
>> typedef BLOCK
>> {
>>   PF * packdata;
>> } BLOCK;
>>
>> BLOCK* blocks;
>> [/code]
>>
>> My first idea was to create a class for PF and a class for BLOCK, but
>> I got lost somewhere along the lines. :\
>>
>> Python Attempt: Please note that since I can't type TABs online
>> easily, I am using the @ character to represent TABs in the following
>> Python code.
>> [code]
>> class PF:
>> @def __init__(self):
>> @@self.flags, self.user = 0, 0
>> @@self.filename = ''
>> @@self.buffer = []
>>
>> class BLOCK:
>> @def __init__(self):
>> @@self.packdata = []
>>
>> blocks = []
>> [/code]
>>
>> Any Python Gurus out there that can help me?
> 
> At a first glance it looks okay but unless we know what you are going to
> do with these data structures it's hard to tell if it is really the best
> "translation".
> 
> `PF.buffer` might be better a string

Mmm... We can't tell for sure since we have no use case, but I'm not 
sure that the OP wants an immutable object here.

> or an `array.array`.

or a StringIO.

>  And is `BLOCK`
> really just a structure with *one* member?  Looks a bit odd IMHO.

+1

<OP>
Unless you have behaviours attached to this type, you may as well just 
use lists.
</OP>

And while we're at it, Python's conventions are that ALL_UPPER names 
denotes (pseudo) constants. For types, the conventions is to use 
CantRememberIfItsCamelOrMixedCaseButYouShouldGetTheIdeaByNow.

HTH



More information about the Python-list mailing list