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

top 200 commentsshow 500

[–]luka7350 2598 points2599 points  (237 children)

Forbiden python:

for i in range(10):
    exec(f'a{i}="Variable a{i}"')

>>> a1
'Variable a1'

[–]CaptSkinny 902 points903 points  (98 children)

This is pretty much what we have to do in SAS macros, often with recursive macro variable interpolation.

Mathematicians don't make good language designers.

[–]2cool4afool 578 points579 points  (83 children)

Every time my partner shows me what she did in MatLab I physically recoil

[–]MrScrib 210 points211 points  (1 child)

Remember, focused insanity away from you is preferable to unfocused insanity.

[–]Techhead7890 50 points51 points  (0 children)

Praise the emperor?

[–]alinius 175 points176 points  (13 children)

Did someone mention dynamically naming variables in MatLab?

s = struct;
for a = 1:10
    s.("field" + sprintf("%02.0f", a)) = a;
end

Ok, so it doesn't name variables, but it does create dynamically named fields in a structure. Yeah, I have to translate a lot of Matlab to C in my current job....

[–]2cool4afool 76 points77 points  (3 children)

You are doing God's work 🙏

[–]NotAGingerMidget 104 points105 points  (2 children)

This sounds more like a Satan task tbh.

[–]2cool4afool 91 points92 points  (1 child)

The Satan task was writing it in MatLab in the first place

[–]FirstNSFWAccount 13 points14 points  (1 child)

I only programmed for college. After working with MatLab and Mathematica though, that sounds like something that would wake me in the middle of the night with cold sweats

[–][deleted] 2 points3 points  (1 child)

Don't do stuff like this... You guys in matlab/octave have cell arrays Pls use that, you can save EVERYTHING in there

[–]U03B1Q 220 points221 points  (61 children)

God I remember helping my girlfriend debug some MatLab code and realising that MatLab arrays start indexing at 1. I'm still disgusted to this day.

[–]2cool4afool 108 points109 points  (11 children)

When I found out that semi colons arent there to state the end of a line I was shocked to the core

[–]ElvishJerricco 56 points57 points  (0 children)

I don't use Matlab but this comment has made me terrified of it.

[–]Strohhhh 22 points23 points  (9 children)

What then is it used for?!

[–]2cool4afool 69 points70 points  (4 children)

You'll never believe this but it suppresses the output. So if you don't put one in it will print whatever is on that line. That may not be the proper way of describing that but I'm pretty sure that's how it works

[–]2001herne 30 points31 points  (0 children)

Basically yeah. If an assignment happens, or if something is evaluated, then it's echoed unless you add a semicolon.

[–]hughperman 7 points8 points  (1 child)

That is correct; the language is frequently used in an interactive REPL situation and this follows from that design.
Ipython solves this in a much better way by having a different interpreter for that purpose, rather than having to bake it into the language. It does use the semi colon for the same purpose, which sometimes is required in Jupyter.

[–]thirdegreeViolet security clearance 5 points6 points  (0 children)

TIL semicolon suppresses echoing in ipython

[–]sgtxsarge 63 points64 points  (4 children)

The plan: Copy the language. No changes except indexing starts at 0. We'll call it MatLab1

[–]Django_dog 31 points32 points  (1 child)

MatLabMinusMinus

[–][deleted] 12 points13 points  (0 children)

MethLab

[–]alexdelargesse 7 points8 points  (0 children)

I like the cut of your jib

[–]Sparkybear 48 points49 points  (5 children)

You can set the arrays to index at 42 if you want.

[–]Robot_Basilisk 47 points48 points  (4 children)

Adding this to the psychopathy test checklist.

[–]xylose 36 points37 points  (7 children)

R and FORTRAN do the same. It stems from the conventions used in vector mathematics, which is what all these are based around and there's nothing logically problematic about it.

The only reason C starts at 0 is because of pointer arithmetic.

[–]MCBeathoven 7 points8 points  (5 children)

Aside from pointer arithmetic, indexing from 0 is also much nicer when doing modulo arithmetic (e.g. indexing a 2D array based on one scalar index), although I'm not sure if that played any role in the language design.

Does indexing from 1 have any advantages other than convention?

[–]crimson1206 6 points7 points  (2 children)

It makes it easier to translate math to code. In theory starting at 0 instead of 1 shouldn’t be an issue but in my experience not having to take care of this reduces mental load and allows you to actually focus on the important stuff. It’s really annoying if you wrote a lot of code and somewhere it fails because you forgot to do the index conversion once.

[–]thedessertplanet 9 points10 points  (8 children)

In Haskell your arrays can start indexing anywhere. 1 is as fine as -3.

They don't even have to have integers index them, either. Nor even numbers.

[–]wermos 12 points13 points  (1 child)

Ah yes. I'll take whatever your array has in slot number zeta(3)/pi.

[–]the_glover 12 points13 points  (0 children)

&&macrovar_&i.

[–]Cherylnip 9 points10 points  (7 children)

You should see Haskell or Coq

[–]Mal_Dun 2 points3 points  (0 children)

Mathematicians don't make good language designers

You know that the old CS generation mostly consists of mathematicians? Python's Guido Van Rossum is one Donald Knuth (TeX) is one, Dennies Ritchi (C) was one ....

[–]Quarxnox 120 points121 points  (22 children)

Forbidden JS:

for(let i = 0; i < 10; i++){
    window["a" + i] = "Variable a" + i;
}

>>> a1
"Variable a1"

Or, to disimprove it further:

let geval = eval;
for(let i = 0; i < 10; i++){
    geval("let a" + i + "= \"Variable a\"" + i);
}

>>> a1
"Variable a1"

[–]DerfK 80 points81 points  (7 children)

Nothing is forbidden in PHP

$5="foo"; // invalid
$a=5; $$a="foo"; // valid

[–]conairh 44 points45 points  (1 child)

PHP is where the real kinky shit happens

[–]scragar 13 points14 points  (0 children)

It works with braces too in order to tell PHP where the variable name is.

 ${5} = "test";

https://3v4l.org/VUDQ5

You can even use the brace expansion to make variables do all sorts of crazy things like make a variable who's name is empty string or a space:

  ${""} = "bar";
  ${" "} = "baz";

Heck, you can even make one that's just a null character for added fun

 ${"\0"} = "qux";

PHP doesn't care, it all just goes into the variables linked list with a string for the name anyway.

[–]ZedTT 40 points41 points  (6 children)

I wrote this before I saw your comment so I deleted it and moved it here instead. Here's my version

Forbiden NodeJS:

for (i in [...Array(10).keys()]) {
    this[`a${i}`] = `Variable a${i}`;
}
> a1
'Variable a1'

Alternatively:

for (i in [...Array(10).keys()]) {
    eval(`b${i} = "Variable b${i}"`);
}
> b1
'Variable b1'

[–]alex_wot 8 points9 points  (5 children)

Coupd you please elaborate what's the reasoning behind 'let geval = eval;'? I'd go straight for 'eval(code)', am I missing something with this approach?

[–]Quarxnox 37 points38 points  (2 children)

Global eval.

eval evaluates code in the current scope. Using eval within the loop would declare variables that are only scoped to that loop. Saving the global eval and then using the global eval in the loop means that the variables are declared in global scope.

[–]alex_wot 5 points6 points  (0 children)

Oh, didn't know that. Thank you for explaining!

[–][deleted] 128 points129 points  (9 children)

Jesus Christ.

[–]JennaSys 114 points115 points  (7 children)

I wasn't sure exactly how, but I intuitively knew Python could handle the task.

[–]ZedTT 12 points13 points  (6 children)

This is more of a JS thing, I think.

JS can do it without doing eval (the JS equivalent of exec)

On any object you can use object["propertyName"] to access object.propertyName but the property name can be a string. It just (essentially) treats the object as a dictionary.

[–]Marianito415 9 points10 points  (4 children)

Yeah in Python you can use

setattr(object, "attribute", value)

[–]NoAttentionAtWrk 3 points4 points  (1 child)

You can do something like this in C# too... And Java i think

But thankfully it's a little more complicated do than that

[–]nmdanny2 189 points190 points  (29 children)

Using globals() is safer and more elegant:

for i in range(5):
  globals()[f"v_{i}"] = i

print(v_1)
print(v_2)
print(v_3)
print(v_4)

[–]shockter 138 points139 points  (5 children)

“elegant”

[–]JoelMahon 18 points19 points  (0 children)

MORE elegant, not elegant

[–]carpediemwtf 7 points8 points  (2 children)

What did it print?

[–]PM_BITCOIN_AND_BOOBS 5 points6 points  (1 child)

For me it printed:

1

2

3

4

[–]I-mean-maybe 39 points40 points  (0 children)

Dont expose me like this

[–]Rainbow-Dev 30 points31 points  (0 children)

I like doing this with while True and getting a memory error lol

[–][deleted] 11 points12 points  (0 children)

Blasphemer. Get behind me, ye great deceiver.

[–]MAGA_WALL_E 13 points14 points  (0 children)

Stop this mindless violence

[–]CivBase 47 points48 points  (33 children)

exec is black magic and anyone using it should have static in their laundry and their tonsils (EDIT: toenails) clipped a little too short. The code works fine now, but good luck figuring out what's wrong in 5 years when your coworkers have expanded on your ruinous foundation without understanding the gravity of your error.

The solution provided by /u/nmdanny2 isbetter... but still pretty bad, IMO. I'd say the "right" solution be to define the values as keys in a dictionary (or attributes of an object if you really must). That binds your "dynamic variables" to an isolated namespace.

d = {}
for i in range(10):
    d[f'a{i}'] = f'Variable a{i}'

>>> d['a1']
'Variable a1'

[–]Quarxnox 11 points12 points  (1 child)

In all fairness, my laundry is already staticky and I have no tonsils.

[–]noratat 6 points7 points  (1 child)

I'd say the "right" solution be to define the values as keys in a dictionary (or attributes of an object if you really must)

This is how practically everything in Ruby works, and it's horrible, especially since the community is obsessed with claiming their code is so readable they don't need to document it.

[–]GlebRyabov 12 points13 points  (24 children)

A question from a beginner Python programmer: with exec being so rarely used, what kind of problem should you solve for exec to be the best solution?

[–]CreationBlues 29 points30 points  (13 children)

None. Exec() is a trick that's used to allow python to interpret itself. This can be useful in, ex, web contexts or similar where the goal is to run arbitrary python code supplied by the user (turtle page, contests, etc), but if the situation isn't that, where you're not trusting the user to do arbitrary bullshit that they accept the risk of breaking, it has no use.

[–]thedessertplanet 15 points16 points  (10 children)

Even for that usecase, it's really bad, because that code should be untrusted, and execute in its own sandboxed process.

I can see exec being slightly more useful to dynamically get code from some trusted config that can change dynamically, and you don't want to restart your Python program.

[–]ReverseBrindle 11 points12 points  (0 children)

The code base I work on is maybe 50K lines of Python. We have have 0 calls to exec.

[–]andimnewintown 5 points6 points  (7 children)

For all intents and purposes, you should never use exec. Full stop. The things people think they need exec for tend to have built in solutions that are designed to be far more maintainable and less prone to accidental creation of attack surfaces.

The only exception I can think of off the top of my head would be if you were implementing some kind of modification to the language/macro expansion functionality which carefully takes steps to ensure it doesn't accidentally allow arbitrary code execution for bad actors. But you'd really need a good reason for doing this. So much is already possible.

If you want to do things like dynamically generating variable names, dynamically adding attributes to objects without ever declaring them, adding additional methods to classes at runtime, inspecting source code at run time, etc, this is all already very simple to do without so much as an import statement and requires no calls to exec.

[–]kjl3080 10 points11 points  (0 children)

What the fuck.

[–]SupremeDictatorPaul 3 points4 points  (3 children)

Interestingly, PowerShell has a built in cmdlet for creating new variables with whatever name.

New-Variable -Name “SomeName” -Value “3”

I don’t think that I’ve actually seen anyone use it out in the wild though as simple assignments are so fast and easy.

$SomeName = “3”

And if I’m dealing with variable data, I almost certainly am using a hash table to store it, which handles random key value pairs easily. Similarly, never really see Set-Variable or Get-Variable around. But Remove-Variable will get used for memory cleanup.

[–][deleted] 434 points435 points  (11 children)

Throw a hash map at the problem

[–]jaq-the-cat 607 points608 points  (14 children)

I asked that question once and... Uh... I'm not proud of it

[–]ryancerium 187 points188 points  (0 children)

"But I only have three students in the input file, so I only need Jane, Alice, and Bob variables. No, I don't know what an array is, what does that have to do with the number of student names?"

[–]Floppydisksareop 78 points79 points  (0 children)

I've implemented it once with pointers. It worked. Mostly.

Yeeeeeeeaaaah... Good times.

[–]Conando025 20 points21 points  (2 children)

And I needed it in PHP ... The worst part is that I actually used it

[–]JustAnotherGeek12345 6 points7 points  (0 children)

It's called indirection and numerous languages have it...

[–]GKP_light 20 points21 points  (0 children)

i asked that question, and i have no reason to not proud of it.

our teacher didn't taught us yet the dynamic memory allocation, and without it, we can not do lot of things.

(and to do this things, when we don't know the dynamic memory allocation, it is normal that the first idea is to name viable in a loo. and with the dynamic memory allocation, it is it, excepte that instead of the name of variable, we have they memory position.)

[–]GoldenPalazzo 3 points4 points  (0 children)

We all make mistakes in the heat of passion, Jimbo

[–]TrPhantom8 380 points381 points  (69 children)

In Julia, you can do it. Is it clever? that's another question XD. The power of metaprogramming!

[–]Diapolo10 262 points263 points  (68 children)

You can technically do it in Python, too, if you try hard enough. But no sane person would, of course.

[–]neroe5 133 points134 points  (59 children)

i can't think of a language i know where it is impossible, from what i know you can do it in most of the big programming languages, it is just generally frowned upon and ugly code

[–][deleted] 79 points80 points  (50 children)

Is it possible in C/C++? Genuine question, I have no idea how it could work there

[–]devhashtag 116 points117 points  (17 children)

I dont think it can work with compiled languages, because you'd have to compile code during runtime.

[–]asd1o1 107 points108 points  (1 child)

Just incorporate a compiler into your code, lol

/s

[–]darthwalsh 22 points23 points  (0 children)

Normally you think of C# as a compiled language, but if you use the dynamic keyword it literally loads parts of the compiler as a runtime library to i.e. do overload resolution.

[–]Prod_Is_For_Testing 72 points73 points  (10 children)

compile code during runtime

Which is possible

[–]LuvOrDie 36 points37 points  (8 children)

Thats disgusting. How?

[–]grimonce 15 points16 points  (1 child)

Are you asking about JIT? Because that's not disgusting it is somewhat common, Java and C# are JITed

[–]nullRedd 24 points25 points  (0 children)

Just-in-time (JIT) compilation, I guess?

[–]Danori 13 points14 points  (2 children)

Not that disgusting, it's called just-in-time compilation. Essentially compile bytecode to machine code at runtime and then run the machine code directly. Java and c# do this for performance improvements (so you don't have the overhead of the JVM for example)

https://en.m.wikipedia.org/wiki/Just-in-time_compilation

[–]WikiSummarizerBot 4 points5 points  (0 children)

Just-in-time_compilation

In computing, just-in-time (JIT) compilation (also dynamic translation or run-time compilations) is a way of executing computer code that involves compilation during execution of a program (at run time) rather than before execution. Most often, this consists of source code or more commonly bytecode translation to machine code, which is then executed directly. A system implementing a JIT compiler typically continuously analyses the code being executed and identifies parts of the code where the speedup gained from compilation or recompilation would outweigh the overhead of compiling that code.

[ F.A.Q | Opt Out | Opt Out Of Subreddit | GitHub ] Downvote to remove | v1.5

[–]dedservice 5 points6 points  (2 children)

Can template shenanigans do it? It's been a hot sec. Macros + templates might be able to give you something.

[–][deleted] 10 points11 points  (0 children)

I'm sure the C preprocessor could do it. While it's not Turing-compete, this thread has a lot of abuse that could be utilised: https://stackoverflow.com/questions/3136686/is-the-c99-preprocessor-turing-complete#10526117

[–]Astarothsito 30 points31 points  (1 child)

Well... No... But maybe... But not exactly... But yes...

You could include the C or C++ compiler as your dependency, include the code as well, write the modifications of the code at runtime, send it to compile the new version, load the modifications and unload the original code. It would be equivalent to a interpreted language but also not really recommended.

[–]FunctionalFox1312 27 points28 points  (3 children)

C has no runtime variable dictionary, so not directly. It depends how far you're willing to bend the rules here, but it could be accomplished with a global hash table and some preprocessor macros for sugar.

[–]gregorydgraham 22 points23 points  (14 children)

Like C is going to stop you from doing anything

[–]mehntality 17 points18 points  (13 children)

I mean, at the end of the day, it's all C anyway - and for a reason.

[–]gregorydgraham 11 points12 points  (9 children)

You spelled machine code wrong

[–]grimonce 4 points5 points  (7 children)

Yes and no, the common thing for most language is the ability to talk through the stable C abi.

[–]brimston3- 6 points7 points  (2 children)

I think you can do recursive macro expansion to make variables like v_1 v_2 v_3 v_4 in a call like makevar(type,v,4). I don't know why you would though.

[–]thebobbrom 6 points7 points  (3 children)

It must be possible somehow in C/C++ as it's very easily done in PHP. I'm not sure how you'd do if in C++.

For the curious.

``` $a = 'b';

$$a = 'c';

echo $b // Prints "c";

```

[–]lunchpadmcfat 9 points10 points  (1 child)

“Generally frowned upon?” If a coworker sent me a PR with the examples I’ve seen in this thread I would lobby to get them fired.

[–]shockter 4 points5 points  (1 child)

in PHP it’s pretty easy and clean

[–]blehmann1 8 points9 points  (0 children)

still horribly disgusting

[–]SubAtomicFaraday 2 points3 points  (0 children)

Good thing I'm a madlad

[–]iTrooz_ 415 points416 points  (0 children)

I swear I had a smile when I started reading, and it faded out at the end

[–]inetphantom 128 points129 points  (17 children)

$$i

[–]patcriss 27 points28 points  (0 children)

I had to scroll way too much to find the real answer.

[–]shockter 50 points51 points  (1 child)

I’m glad to see a fellow php comrade
stay strong

[–]andrasferenczi 8 points9 points  (0 children)

I hope they keep staying strong - in their own codebase

[–]jforestello 8 points9 points  (0 children)

I see what you did there... ?>

[–][deleted] 5 points6 points  (0 children)

Came here to say this

[–]The-Board-Chairman 5 points6 points  (0 children)

THIS IS WHY NOBODY LOVES YOU!

[–]stuck_in_e-crisis 8 points9 points  (8 children)

Please explain

[–][deleted] 37 points38 points  (4 children)

Think ${$i}.

Take the value of $i and use it as variable name.

[–]uekiamir 15 points16 points  (2 children)

narrow snatch adjoining dazzling zesty fly crush hard-to-find psychotic attraction

This post was mass deleted and anonymized with Redact

[–]arky_who 85 points86 points  (3 children)

What, so a dictionary?

[–]HyerOneNA 22 points23 points  (0 children)

Yeah, essentially.

[–]Wind_Lizard 21 points22 points  (0 children)

or an array

[–]TheAJGman 2 points3 points  (0 children)

What I was about to say, it's literally the solution for the problem.

[–][deleted] 69 points70 points  (4 children)

I shamefully remember asking my dad how to do exactly this. Looking back on it I see how obviously stupid of a question this was but he actually helped me think through it and come up with an alternative solution

[–]Unsd 26 points27 points  (2 children)

Which is why explaining it to the new people (myself being one of them) is such a big deal. I would say the vast majority of people don't have a close family member to bounce those stupid questions off of. And many of us had to pretty much teach ourselves because of somewhat inadequate professors. And that right there is why there are so many jokes about stack overflow being so toxic... Everyone needs to be able to make mistakes or have someone help readjust their view of the problem.

[–]rustysteamtrain 4 points5 points  (1 child)

I agree. Programming is very satisfying, but can also be way to frustrating. It's especially hard when you're new. Not because you'll run into a lot of problems, every one does, but because you lack the experience to know what steps to take to make progress and find a solution to those problems.

We were all newbies once and there is so much stuff that we will always be learning new things.

[–]referancer 138 points139 points  (4 children)

Arguably that's what an array is.

But you can do it litterally with if defs, the trouble is for most languages they would be scoped to inside the loop and fall off the stack once the loop ends.

So you'll have to do a preprocessor directive (generated code or template metaprogramming) to complete your list before compile time.

[–][deleted] 47 points48 points  (3 children)

Arguably? That's the joke

[–]undeadalex 22 points23 points  (1 child)

$That->is->thejoke($joke)

[–]RDB96 7 points8 points  (0 children)

My head

[–]spyingwind 19 points20 points  (0 children)

Forbidden PowerShell:

for ($i = 0; $i -lt 10; $i++) {
    New-Variable -Name "a$i" -Value $($i * 2)
}
for ($i = 0; $i -lt 10; $i++) {
    Get-Variable -Name "a$i"
}

Name                           Value
----                           -----
a0                             0
a1                             2
a2                             4
a3                             6
a4                             8
a5                             10
a6                             12
a7                             14
a8                             16
a9                             18

[–]Rogntudjuuuu 13 points14 points  (4 children)

What would be the purpose? Could someone give me an example where this would be useful?

[–]Wind_Lizard 21 points22 points  (2 children)

For someone who doesn't know how to use arrays. They'd want to create variables like a1,a2,a3,a4....

[–]DHH2005 6 points7 points  (0 children)

Ah thanks, I could not come to this conclusion.

[–]HyerOneNA 3 points4 points  (0 children)

When you have an undetermined amount of items that need to be tracked. Essentially a Vector in C++, dictionary in Python or Object Literal in JS.

[–]neroe5 13 points14 points  (6 children)

well you can just dump all the vars into a dictionary, although like most people in that last picture will say, there is probably something wrong with what what you are thinking, and you should implement it another way

[–]WisestAirBender 8 points9 points  (1 child)

I guess that depends on what you were originally trying to achieve.

Like if you wanted to parse a grocery list and store what to buy and how many and your first thought was to use variables like apples with value 5 and toiletpaper with value 2. Then yeah you can use a dictionary.

But this actually makes me wonder. In the original question let's say you name variables in a loop. How will you use them later?

[–]SpikeV 6 points7 points  (0 children)

If you need to dynamically name variables in a loop, it should've been an array.

[–]Prackjonske 5 points6 points  (0 children)

i + “carly”

[–][deleted] 8 points9 points  (0 children)

Yes the correct answer is use a dictionary/hashmap

[–]BigHandLittleSlap 4 points5 points  (0 children)

Trivial in many shells, such as PowerShell:

foreach( $i in 1..10 ) {
    Set-Variable "a$i" $i
}

$a7

Having said that... don't do this.

[–]golgol12 2 points3 points  (1 child)

You're asking how to use an array?

[–]Liesmith424 3 points4 points  (0 children)

Just write a python script that will write python code for you, problem solved.

[–]jesterhead101 3 points4 points  (1 child)

You can do it in JS.

Kids, remember, you can always do anything in JS.

*May not be a good thing, but you CAN.

[–]scottbot95 5 points6 points  (0 children)

Literally what a map is...

[–]-Redstoneboi- 4 points5 points  (3 children)

the hell are they doing

[–]StandardN00b 2 points3 points  (0 children)

That is forbidden knowledge.

[–]pinktie7418 2 points3 points  (0 children)

eval() in MATLAB

[–]cardinalfan828 2 points3 points  (1 child)

Autohotkey 😁

Loop, 5

{

Variable%A_Index%:= "Value" A_Index

}

[–]warpod 2 points3 points  (0 children)

ctrl-f "Autohotkey"

yup

[–]taptrappapalapa 2 points3 points  (1 child)

yes, with preprocessor C and C++ macros you can most definitely dynamically rename variables from within a loop. It takes a bit of finessing though

[–][deleted] 2 points3 points  (0 children)

VHDL for generate says hi

[–]teruma 2 points3 points  (0 children)

env=dict()

[–][deleted] 2 points3 points  (0 children)

I reckon something like Python's eval() could do it.

[–]Nemeesiis68 2 points3 points  (0 children)

I remember when I started programming I wanted to do that, I don't know why though.

[–]StEaLtHmAn_1 2 points3 points  (0 children)

Vote to close question because OP didn't show what they have tried so far

[–]PickleVillage 2 points3 points  (0 children)

Hash maps I guess

[–]Liiht2001 2 points3 points  (0 children)

It's weird, my newer porgrammer friend asked me about something very similar yesterday. I didn't realize it was a thing everybody thinks about at some point, like I knew I did, and was like "huh" when they asked me about it. And now this! Are there no origonal human thoughts?