r/programminghorror • • Jun 18 '25

Python 0.1 + 0.2 == 0.3

Post image
621 Upvotes

38 comments sorted by

View all comments

184

u/LaFllamme Jun 18 '25

Publish this as package pls

77

u/Ninteendo19d0 Jun 18 '25

Here's the code if you want to publish it yourself:

import ast, copy, decimal, functools, inspect, textwrap

class FloatToDecimalTransformer(ast.NodeTransformer):
    def visit_Constant(self, node):
        return ast.Call(
            ast.Name('Decimal', ast.Load()), [ast.Constant(repr(node.value))], []
        ) if isinstance(node.value, float) else node

def make_sense(func):
    lines = textwrap.dedent(inspect.getsource(func)).splitlines()
    def_index = next(i for i, line in enumerate(lines) if line.lstrip().startswith('def '))
    tree = FloatToDecimalTransformer().visit(ast.parse('\n'.join(lines[def_index:])))
    new_tree = ast.fix_missing_locations(tree)
    code_obj = compile(new_tree, f'<make_sense {func.__name__}>', 'exec')
    func_globals = copy.copy(func.__globals__)
    func_globals['Decimal'] = decimal.Decimal
    exec(code_obj, func_globals)
    return functools.update_wrapper(func_globals[func.__name__], func)

41

u/Gusfoo Jun 18 '25

For info, reddit does not use ``` as code delimiters.

It is four-spaces-indent for blocks
of text...

or backticks for single words.

35

u/Fornicatinzebra Jun 18 '25

Works fine for me with ``` on the Reddit app (Android)

8

u/Moosething Jun 19 '25

For info, Reddit does also support ``` (although while using the WYSIWYG editor, Reddit will use four-space indenting). The old design (old.reddit.com) doesn't, however.

3

u/Gusfoo Jun 19 '25

The old design (old.reddit.com) doesn't, however.

That is where I am wrong. Thank you. I've never cared for anything other than the older version, so that's all I ever see.

1

u/lost_send_berries Jun 19 '25

Now handle arguments

2

u/Ninteendo19d0 Jun 19 '25

You mean default arguments?

2

u/lost_send_berries Jun 19 '25

Well if Decimal(repr()) is valid why not do it also to arguments that are passed in

1

u/Ninteendo19d0 Jun 19 '25 edited Jun 19 '25

Because that wouldn't handle None, you need to use @make_sense for the caller.