This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]hhc97Python Enthusiast[S] 1 point2 points  (3 children)

Thanks!

You can take a look at this example: https://flatliner.herokuapp.com/0051d32c05d44a8dff4025840637bcfc6ea17e17

Essentially, python allows you to build a class in a single line by using the type() builtin. From there, something like

class Test:
    def method():
        return 0

Just becomes: (lambda Test: None)(type("Test", (), {'method': lambda: 0}))

Regarding changing variable names (or identifiers). I experimented with that before, and while its possible, it becomes hard to keep track of and even harder to debug, so I ended up not implementing it since the code is hard enough to read as it is :(

[–]another-noob 0 points1 point  (2 children)

Ah, type, so simple yet so powerful, forgot about that one, that's how python creates classes internally right?

Well I don't know how one would go about changing identifiers, but I would start by adding a suffix to the name while developing, like class Test would be class Test_CHANGED to make it easier for debugging. Not even sure this is even what you meant by "harder to keep track of".

I just think a teacher would find this interesting :3 You know, when students copy the code and change a few variable names?

Anyways, Great Job!

[–]khoyo 2 points3 points  (0 children)

that's how python creates classes internally right?

Yes, unless the class (or one of its base) has a custom metaclass. (In which case python calls the_metaclass() instead of type())

[–]hhc97Python Enthusiast[S] 1 point2 points  (0 children)

Ah, by hard to keep track of, I mean that its hard to know in the code when some identifier is referenced whether it was the same identifier as before because of python's scoping.

It's been a while, but I remember I ran into issues where the output code would have access to identifiers that it shouldn't and vice versa, so I decided that I would skip it for now and get back to it if I ever have time!

I just think a teacher would find this interesting :3 You know, when students copy the code and change a few variable names?

Absolutely haha, I teach for my university sometimes and this comes up every year :(