Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
307 views
in Technique[技术] by (71.8m points)

python - How to make "int" parse blank strings?

I have a parsing system for fixed-length text records based on a layout table:

parse_table = [
    ('name', type, length),
    ....
    ('numeric_field', int, 10), # int example
    ('textc_field', str, 100), # string example
    ...
]

The idea is that given a table for a message type, I just go through the string, and reconstruct a dictionary out of it, according to entries in the table.

Now, I can handle strings and proper integers, but int() will not parse all-spaces fields (for a good reason, of course).

I wanted to handle it by defining a subclass of int that handles blank strings. This way I could go and change the type of appropriate table entries without introducing additional kludges in the parsing code (like filters), and it would "just work".

But I can't figure out how to override the constructor of a build-in type in a sub-type, as defining constructor in the subclass does not seem to help. I feel I'm missing something fundamental here about how Python built-in types work.

How should I approach this? I'm also open to alternatives that don't add too much complexity.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use a factory function instead of int or a subclass of int:

def mk_int(s):
    s = s.strip()
    return int(s) if s else 0

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...