anupam
anupam

Reputation: 91

custom format specifications in python

in python, how can a custom format-specification be added, to a class ? for example, if i write a matrix class, i would like to define a '%M' (or some such) which would then dump the entire contents of the matrix...

thanks

Upvotes: 2

Views: 1208

Answers (3)

Tendayi Mawushe
Tendayi Mawushe

Reputation: 26128

If you really want to use custom specifiers you cannot do this in way that compatible with the rest of the Python language and standard library. Take advantage of what Python already supplies (%s and %r) and customise it for your needs by overriding __str__() or __repr__()

class Matrix(object):
    def __str__(self):
        return convert_to_pretty_matrix_string(self)
    def __repr__(self):
        return convert_to_textual_matrix_format(self)

Upvotes: 0

rldrenth
rldrenth

Reputation: 35

I don't believe that it's possible to define a new format specifier for print. You might be able to add a method to your class that sets a format that you use, and define the str method of the class to adjust it's output according to how it was set. Then the main print statement would still use a '%s' specifier, and call your custom str.

Upvotes: 0

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799082

Defining the __str__()/__unicode__() and/or __repr__() methods will let you use the existing %s and %r format specifiers as you like.

Upvotes: 5

Related Questions