What is an acceptable python alternative for C ++ overloaded stream stream operators?

In C ++, you can do this to read the data in the class easily:

istream& operator >> (istream& instream, SomeClass& someclass) {
    ...
}

      

In python, the only way I can find to read from the console is with the "raw_input" function, which is not very suitable for this kind of thing. Is there a pythonic way to do this?

+2


source to share


3 answers


No, there is no widespread Pythonic convention for "read the next instance of class X from this plain text input file". I believe this applies to most languages, including, for example, Java; C ++ is the kind of outlier out there (and many C ++ stores prohibit use operator>>

in their local style guides). Serialization (to / from JSON or XML if you want ostensibly readable text files) suggested by the other answer is one possible approach, but not too hot (a standardized way to serialize fully generic class instances to XML or JSON).



+3


source


You are essentially looking for deserialization. Python has many options for this, depending on the library used. The default is python etching . There are many other options that you can check out here .



+6


source


Instead of using raw_input, you can read the sys.stdin file (a file-like object):

import sys
input_line = sys.stdin.readline()
# do something with input_line

      

+2


source







All Articles