Spyke
programmerhumor·Programmer Humorbyraldone01

Using comments as arguments in python.

Python allows programmers to pass additional arguments to functions via comments. Now armed with this knowledge head out and spread it to all code bases.

Feel free to use the code I wrote in your projects.

Link to the source code: https://github.com/raldone01/python_lessons_py/blob/v2.0.0/lesson_0_comments.ipynb

Image transcription:

# First we have to import comment_arguments from arglib
# Sadly arglib is not yet a standard library.
from arglib import comment_arguments


def add(*args, **kwargs):
    c_args, c_kwargs = comment_arguments()
    return sum([int(i) for i in args + c_args])


# Go ahead and change the comments.
# See how they are used as arguments.

result = add()  # 1, 2
print(result)
# comment arguments can be combined with normal function arguments
result = add(1, 2)  # 3, 4
print(result)

Output:

3
10

This is version v2.0.0 of the post: https://github.com/raldone01/python_lessons_py/tree/v2.0.0

Note:

v1.0.0 of the post can be found here: https://github.com/raldone01/python_lessons_py/tree/v1.0.0

Choosing lib as the name for my module was a bit devious. I did it because I thought if I am creating something cursed why not go all the way?

Regarding misinformation:

I thought simply posting this in programmer humor was enough. Anyways, the techniques shown here are not yet regarded best practice. Decide carefully if you want to apply the shown concepts in your own code bases.

View original on lemmy.world
thelemmy.club

IMO comments should never ever be parsed under any circumstances but I probably don't know enough to really speak on this

204
lemmy.world

Seen in a code review (paraphrased):

"Why does this break when you add comments in the middle?"

62
bleistift2reply
sopuli.xyz

Why would python even expose the current line number? What’s it useful for?

17

On a serious note:

This feature is actually very useful. Libraries can use it create neat error messages. It is also needed when logging information to a file.

You should however never ever parse the source code and react to it differently.

38
lemmy.ml

Why wouldn't it? Lots of languages do. In C++ you have __LINE__.

17

Because it doesn't seem like a useful feature. The only occasion I imagine this could be helpful is with logging to the console to track when the function breaks, but even then - still trivial to replace.

-3
lemmings.world

That's horrible. Every sane person would filter out lines containing comments to find the correct index.

8

This should be a build step. Preprocess before the preprocessor. All line number will be off depending on the comments. 😂

Unless...

C with source maps!!! Thank js for the cool solution.

6

The add function in the example above probably traverses the call stack to see what line of the script is currently being executed by the interpreter, then reads in that line in the original script, parses the comment, and subs in the values in the function call.

This functionality exists so when you get a traceback you can see what line of code triggered it in the error message

18
jaxxedreply
lemmy.world

Can we just clarify that you mean that comments should never be parsed by the language engine. There are valid annotation systems, but the goal is alway to ensure that one passable can never impact the other.

Imagine if here a comment could create a syntax error! This is even worse for runtime scripting languages like python.

8
bastionreply
feddit.nl

Sure, but let's just clarify that this is someone going out of their way to create this problem, using Python's ability to read it's own code.

Basically, you can load any text file, including a source code file, and do whatever you want with it.

So, a function can be written that finds out whatever's calling it, reads that file, parses the comments, and uses them as values. This can also be done with introspection, using the same mechanism that displays tracebacks.

9
Artyomreply
lemm.ee

This isn't standard python. lib is not in the standard library. Python also doesn't have any special variables where it stores comments, other than __doc__ which stores a docstring. If I had to guess, add is reading the file/REPL via __file__.

5

It's a string, although sometimes Python conflates the two. The recommended way to make a multi-line comment is to just make a multi-line string and just don't use it.

2
Rookireply
lemmy.world

Comments should be removed before shipping.

4
ludreply
lemm.ee

Python is an interpreted language but for a compiled language absolutely (and obviously).

7

Well now that causes breakage two dependencies down the line. Good luck with that. 😅

4
ahalreply

Ignoring lint issues comes to mind as an at least somewhat reasonable use case.

3

One case where I find it useful, tho it operates in a more limited way, is code in block blocks within code comments in Rust, which are also printed out in the generated documentation. They essentially get ran as part of your unit tests. This is great for making sure that, eg, your examples left in code comments actually work, especially if they’re written in a way that functions like a unit test.

3
balsoftreply
lemmy.ml

It's quite useful to parse comments and generate documentation from them, either as plain old hypertext or in your editor with LSP.

2
ramble81reply
lemm.ee

That sounds fine if you have something reading the file independently. But the actual executable code should not be able to access its own comments.

5

Comments aren't normally accessible unless you (independently) open and read the source code file as you would with any arbitrary file.

1

capability is fine. Conflation is stupid. You can also use code to erase itself, but thinking that's a good idea is generally wrong. But to remove that, you also remove the general ability to erase files.

1

Some languages use the comments to generate documentation. Something like

// function to add two numbers func Add(num1 int, num2 int)

2

I assume the people freaking out about how dumb python is didn't bother to read the code and have never coded in python in their life, because the behavior here is totally reasonable. Python doesn't parse comments normally, which is what you'd expect, but if you tell it to read the raw source code and then parse the raw source code for the comments specifically, of course it does.

You would never, ever accidentally do this.

...you'd also never, ever do it on purpose.

67
Swedneckreply
discuss.tchncs.de

yeah frankly this post is borderline misinformation, they specifically import a library to read comments as arguments, it's like redefining keywords in C and complaining about C being dumb

25
CanadaPlusreply
lemmy.sdf.org

I'm going to say it just is misinformation, if that's what "lib" is here.

12
bastionreply
feddit.nl

Yeah. 'lib' isn't a standard Python library, it's the name of the abomination that this person created. Since python has quite a bit of useful introspection, they can do something like:

  • get the stack
  • find the exact call to abomination.add()
  • reparse the text of that line, turn the text of the comment into actual numbers, and add them

Now, I don't know if python keeps the comments around, so it may involve getting the filename and line number, reading the file, and manually extracting the comment text from that line.

4
CanadaPlusreply
lemmy.sdf.org

It's not even actually called lib. The line just straight up isn't in the image "transcribed", and it's from arglib import comment_arguments in the original code.

Yeah, I gave this one a downvote.

4
raldone01reply
lemmy.world

I updated the source after this post was made. The image transcription still holds. I did not update the image and the post text.

You can view the git history. I will tag the specific commit at the time of the post later and update it accordingly.

2

Ah, and you're the author. That kind of changes the whole context here.

It doesn't mean much, but have your upvote back.

2

Yup, the function actually goes and finds the code that calls it and parses the comment.

Disgusting.

30
lemmy.dbzer0.com

The add() function (that is available in the source code) basically uses some built in debugging tools to find out where in the code the function is called, and then parses the comment from the file and uses it for adding stuff.

I’ve never tried (becuse why would you…) but something similar can probably be built in any interpreted language

It’s not something Python does by design

52
N0x0nreply
lemmy.ml

Thanks :) ! Could you tell me what use case/purpose such function can have from a dev perspective?

9

This stuff is normally used for creating human readable error messages. E.g. printing the line of your code that actually set off the exception

10

I'd say nothing that can't be achieved by docstrings.

7
lemmy.dbzer0.com

This specific use case? To make a meme, mainly ¯\(ツ)

As for the components: Parsing comments have been used for stuff like type hints / formatting / linting, tho generally not at run time (afaik).

The tooling for finding out where something is called from can be used to give a better understanding of where things go wrong when an exception happens or similar, to add to logs.

I would say that in general you don’t need either functionality except for certain edge-usecases

7

We actually use method comments for user documentation as well. Only on specific business methods, but it's nice to have a good comment for the dev and a tooltip for the user at the same time.

3

they have to import a separate library to do this, it's not a part of standard python, and this post is basically just misinformation

1

It's actually kind of nice to see this as a JS developer.

Not like, "Oh wow this is neat!"

But like, "Finally the golden child, Python, also has some fucked up shit"

9

This is an affront to nature. Comments shouldn't even make it past the scanner.

39

You can so stupid shit in any language. I admit Python doesn't exactly make it difficult. A bit like JS, but different.

22
verdigrisreply
lemmy.ml

Being able to get the line number is very different from comments being parsed.

Edit: didn't realize this was custom code built to be cursed.

3
bjorneyreply
lemmy.ca

You should look at how OPs example works first maybe

The python interpreter isn't parsing comments, the add() function is just getting the current line number from the call stack context, and using a regex to spit out the numbers to the right of the "#" on the current executing line of the source code.

17

Yeah fair I was just assuming this was standard library, I see your point now.

4
Doxinreply
pawb.social

Because whoever wrote this went to great lengths to make it work. It's by no means a feature of python. It's a feature of their code.

5

No it isn't. Go try it without including any of this guys code. Don't be a troll.

1
lemm.ee

I hate this shit being routinely used in PHP. Symfony uses those functional comments for routing, essentially scanning every controller file as text on every visit, to gather the url patterns above functions. Laravel uses Reflection, which is functionally the same thing, to provide arguments to controller functions. Also, kind of related, the project I'm working now has few functions that use backtrace to return different results based on where they are called from. It is indeed very cursed and I'm ripping out any usages of them whenever I see one.

13

Comment Annotations were a nessecary thing as php did not support a native way to do it. However, since php 8, there is now native attributes.

4
lemmy.ml

What? There is no lib module.

$ python3.13 -c 'import lib'
Traceback (most recent call last):
  File "<string>", line 1, in <module>
    import lib
ModuleNotFoundError: No module named 'lib'
$
12
b34kreply
lemmy.ml

OP wrote this add() function and has provided their own lib module in the source code.

16

Oh, so it’s not Python that’s cursed.

One of Python’s design philosophies is—or at least was—“we are all consenting adults here.” If you really want to turn Python into Brainfuck, the interpreter isn’t going to stop you.

23
Swedneckreply
discuss.tchncs.de

because OP wanted upvotes, this isn't actually part of python in any way, it's using a custom library to do it.

2

Yeah. This post was made to show off something cursed I created.

I have already updated the repo to make it more obvious this is not standard Python. I will do the same with the post.

1

Hmm, works in php as well!

function add(): float
{
    $trace = debug_backtrace();
    $file = $trace[0]['file'];
    $line = $trace[0]['line'];

    $content = file($file);
    $lineContent = trim($content[$line - 1]);
    $ast = token_get_all("<?php\n{$lineContent}");

    $args = [];
    foreach ($ast as $token) {
        if (!is_array($token)) {
            continue;
        }
        if ($token[0] !== T_COMMENT) {
            continue;
        }

        $commentContent = $token[1];
        if (str_starts_with($commentContent, '#')) {
            $commentContent = substr($commentContent, 1);
        } else {
            $commentContent = substr($commentContent, 2);
        }
        $commentContent = trim($commentContent);
        $commentContent = preg_replace("@\s+@", " ", $commentContent);
        $args = explode(" ", $commentContent);
        $args = array_map(function (string $arg) {
            if (!is_numeric($arg)) {
                throw new InvalidArgumentException('Argument must be a number');
            }

            return str_contains($arg, '.') ? (float) $arg : (int) $arg;
        }, $args);
        break;
    }

    return array_sum($args);
}


echo add(); // 1 2 3
echo add(); // 7 8 9
5
raldone01reply
lemmy.world

Love this. I am toying with an idea of how to accomplish this in rust.

1
lemmings.world
use std::fs;

fn add_from_comment(file: &str, line: u32) -> f64 {
    let source = fs::read_to_string(file).expect("Failed to read source file");

    let source_line = source.lines().nth((line - 1) as usize).expect("Line not found");

    if let Some(comment_start) = source_line.find("//") {
        let comment = &source_line[comment_start + 2..].trim();
        let numbers: Vec<f64> = comment
            .split_whitespace()
            .map(|num| num.parse::<f64>().expect("Invalid number in comment"))
            .collect();

        return numbers.iter().sum();
    }

    0.0
}

macro_rules! add {
    () => {
        add_from_comment(file!(), line!())
    };
}

fn main() {
    let result = add!(); // 7 8 9
    println!("{}", result); // Outputs: 24
    
    let result2 = add!(); // 1 4 3
    println!("{}", result2); // outputs 8
}
4

Nice I would have tried it with a build script but this works too. Good job!!!!

1

The best language is complete, succinct, orderly and clear. And never adds a single goddamn thing ever.

4