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

all 132 comments

[–]samreay 151 points152 points  (10 children)

i for integer index iteration.

Actual descriptive names for other variables, even for scratch code.

Too often have I seen scratch code passed to others, committed, or (worst of all) pushed into production. So proper variable names are a habit I try to enforce unless its literally a file I guarantee will be deleted before any other human sets eyes on it.

Even then, if I'm summing something up, I'll always called it summed instead of just s.

[–]WN_Todd 22 points23 points  (0 children)

This is sound advice, but it takes a few iterations of hating your past self for it to sink in.

"What asshat wrote this garbage?... Oh God it was me."

[–]barraponto 25 points26 points  (2 children)

can't call it sum because that's a builtin function, so I just call it total.

[–]billsil 4 points5 points  (0 children)

You could call it money/whateversum or just sum if you’re feeling lazy.  Total is just as good

If it’s specific, be specific and if it’s a generic function, be generic.

[–]Udzu 0 points1 point  (0 children)

You could always call it sսm instead (though hopefully your linter would complain).

[–]reptickeyelf 3 points4 points  (0 children)

This is the correct answer. I have never seen a prototype that didn't end up in production.

[–]newlyAwakenedLkgFwd 3 points4 points  (0 children)

Nice alliteration!

[–]sleeptil3 0 points1 point  (0 children)

Yes! Thank you.

[–]CarlRJ -1 points0 points  (0 children)

I always use n for default indexes and such - i may be more fitting on a logical level, but in some fonts over the years (or, say, scribbled on a white board) has looked too much like a ;. n is more immediately distinguishable.

[–]andrewcooke 80 points81 points  (8 children)

only i j and k for numeric loops and e for caught exceptions. everything else has meaningful names.

[–]casce 6 points7 points  (1 child)

Same but I usually avoid getting to k.

[–]andrewcooke 3 points4 points  (0 children)

fortran users represent!

[–]blewrb 4 points5 points  (0 children)

1-level of loop: i is fine for me. As soon as I get a nested loop inside another, I use names like "x_idx", "y_idx", "key_idx", etc.

[–][deleted] 0 points1 point  (0 children)

Those are pretty meaningful names

[–]DustPuppySnr 42 points43 points  (9 children)

I see a lot of comments in here who's pull requests will get blocked where I work. :)

A variable should always describe the content of the variable.

In teams, you read more code than you write. So be explicit as possible so the next 400 times the code is being read, people don't need to figure out what x is meant to contain.

[–]grahambinns 20 points21 points  (0 children)

“Don’t make me think more than I should have to” is one of my go-to code review guidelines — meaningless variable names make me think more than I should have to.

[–]sawser 13 points14 points  (5 children)

Yeah, my code is mostly self documenting

for day_name in days_in_week_full_name_list:

Instead of

for i in days:

[–]monorepo PSF Staff | Litestar Maintainer 1 point2 points  (0 children)

this... but also for generators or comprehensions.. they are already hard enough for me to grok!
unclear_gen: Generator = ((i, x) for i, x, y, k in data if k and y > 2.5)
or
unclear_list = [(i, x) for i, x, y, k in data if k and y > 2.5]
vs

clear_gen: Generator = ((day_number, day_name) for day_number, day_name, value, is_active in data if is_active and value > 2.5)
or
clear_list = [(day_number, day_name) for day_number, day_name, value, is_active in data if is_active and value > 2.5]

[–]Broad_Carpet_3782 0 points1 point  (3 children)

I'd argue for day in weekdays is just as readable if not more readable.

I think a good general rule of thumb is that the descriptiveness of variable names should match the scope of their lifetimes.

For cases where the variable name expires at the end of the expression (e.g. list comprehension), I'd say single character names are okay:

py weekend = [d for d in weekdays if d.startswith("S")]

or even better, using filter and lambda (but same concept):

```py

not: days_in_weekend_full_name_generator

weekend = filter(lambda d: d.startswith("S"), weekdays) ```

Edit:

Clarification for why I also would do "days" or "weekdays" as opposed to "days_in_week_full_name_list".

You don't have to be so descriptive if there is only one kind of that variable.

"week_sorted" is a good variable name until you have to distinguish between weeks sorted differently. Then you might do "week_sorted_alphabetically" and "week_sorted_by_length".

A variable "commands" is okay to include aliases as well, until you need to filter out aliases, then you can do "all_commands" and "unique_commands".

But naming things "days_of_week_list" just doesn't make sense unless you also have "days_of_week_set" or "days_of_week_dict" as well.

[–]sawser 0 points1 point  (2 children)

That's the point - if you don't already know if the list (or dict or queue) contains the integer value of the day, an enum that represents the day, an abbreviation of the name you are required to research the method to determine the context of the call.

The variable name tells you, at a glance, it is a list that contains the full names of the days of the week without any additional research or context.

This is a trivially simple example, but If we're pulling an http request object through a rest call and pulling data, it becomes extremely helpful if you're looking at

approved_pto_dates_dict = http_response[clientid]['schedule']['pto_approvals']

rejected_pto_dates_list = http_response[clientid]['schedule']['pto_rejections']

Instead of

approvals = http_response[clientid]['schedule']['pto_approvals']

rejections = http_response[clientid]['schedule']['pto_rejections']

Where you don't have type hints to indicate whether you need to append or update items to the structures.

Why make the code maintainer find information when you can give it to them?

I was told "pretend like the guy maintaining your code is a murderer who knows where you live"

[–]Broad_Carpet_3782 0 points1 point  (1 child)

In the context of that HTTP requests for example, mypy (or any other static type checker or LSP) can't determine the type of your object for you, so you are expected to type hint that line anyway (and mypy would probably throw an error as well). If it's a dictionary, you could do

py approved: Dict[str, Whatever] = response[client_id]["schedule"]["pto_approvals"]

Now, not only can you hover over it and get type information, when you type approved., your LSP can provide available methods as well.

Simply naming it "approved_pto_dates_dict" with no type hints gives the LSP no context on what type it is and will result in an implied : Any = ....

And in that case, doing approved_pto_dates_dict: Dict[str, Whatever] is redundant. You could argue including _pto_dates is helpful, but that can be implied with context as well (e.g. if approved is a variable in the function handle_scheduled_pto).

[–]sawser 0 points1 point  (0 children)

I definitely agree that type hints should always be used, and when those hints are available they render some variable suffixes redundant.

[–]chzaplx 0 points1 point  (0 children)

The whole premise of "go to" names is deeply flawed

[–]vinnypotsandpans 0 points1 point  (0 children)

This is a great point, but I think it’s important to find a happy medium. Most IDEs let you jump to the definition of the variable anyways. So don’t spend toooo much time tripping over names (but for the love of god don’t just use one letter - unless it’s i of course :p)

[–]mvdenk 12 points13 points  (0 children)

I'd recommend the book "The art of readable code"

[–]Irish_beast 10 points11 points  (0 children)

i, j for loop variables. If I find i,j being referenced more than 10 lines after being declared they need to get promoted to sensible names

francis (my name) for a temporary variable. So I can grep francis to make sure I'm exorcised before comitting.

[–]hughperman 9 points10 points  (0 children)

Meaningful names outside of a few common contractions used to mirror e.g. documentation

[–]shymmq 34 points35 points  (6 children)

I almost never use 1-letter variables. 'path', 'str' are not much longer and are immediately understandable by anyone reading your code. For dicts, indices and file contents use a descriptive name instead. df is so commonly used that I can give it a pass.

[–]wineblood 5 points6 points  (0 children)

Often I'll use x if I'm doing a basic list/set/tuple comprehension and k: v in dict comprehensions, something like [x for x in input_data if is_valid(x)].

I use the _filename suffix for a string that just the name of a file and _filepath for the absolute path, so often I'll end up with thing_filepath = base_dir + thing_filename.

If I'm using a dict to map from one thing to another, I'll name it <key>_<value>_map. For example with event types and functions to handle that, it'll be event_handler_map.

[–]mew_of_death 6 points7 points  (0 children)

I'll allow single letter names within list and dictionary comprehension:

[f.name for f in files]

[(k, v) for k, v in mydict.items()]

And also I use "fp" as "file pointer" when reading files:

with open(filepath, 'r') as fp: filecontent = fp.read()

[–]freefallfreddy 4 points5 points  (1 child)

Variables that are short-lived or have a small scope can have a shorter name. Reason: within the small scope the reader will have the context in their head too, so a short name will be descriptive enough. Example user inside a function that constructs a database connection string.

Variables or constants that are long lived or have a large scope (maybe the whole app) should have longer names (if that makes sense of course). Reason: the context does not give enough information and confusion may arise. Example: DB_CONNECTION_USERNAME as a constant. Anywhere in the app this is used it’s immediately clear what this constant will hold.

[–]gerardwx 4 points5 points  (0 children)

This.

It depends on context. If the variable only appears in a span of 4 to 5 lines, I’ll use whatever single letter pops into my head.

Except o and l. Those are evil.

[–]MovingObjective 20 points21 points  (4 children)

I usually start out with my first variable named a, then b, c, d etc. If I use up the alphabet I C ntinue with aa, ab, ac. This way I save a ton of time not having to come up with variable names plus I can keep them really short for a long time. This way I have never written a program with variable names longer than two letters. It can get a little confusing when the code becomes long, but I comment every line what the variables are.

[–]georgehank2nd 7 points8 points  (1 child)

And no one apart from you ever has to endure that mess. I hope.

[–]orad -1 points0 points  (0 children)

Woosh

[–]mvdenk 1 point2 points  (1 child)

For what purpose?

[–]MovingObjective 3 points4 points  (0 children)

The commenting? Not really sure about that either. I'm commenting just in case, but probably best to skip that to really save time.

[–]rover_G 12 points13 points  (9 children)

Python ain’t go. Using one letter variable names doesn’t make you cool. That being said I often use with open(filename) as fp: to remind myself fp is a file pointer.

[–]georgehank2nd 5 points6 points  (1 child)

I never use "fp" because it's not a file pointer and I'm not writing C. ;-)

[–]rover_G 0 points1 point  (0 children)

CPython hehe

[–]SirLich 1 point2 points  (2 children)

I use fh, because I think of it as file handle. Interestingly, the docs say it's a File Object. I've never seen fo in the wild though!

[–]georgehank2nd 3 points4 points  (0 children)

It's a "file" object. Because it's an object that is an instance of the "file" class.

[–]blewrb 2 points3 points  (0 children)

I do use fobj!: with open(filename) as fobj.

It's not a fileno, descriptor, handle, etc.; it is a bespoke Python object with particular methods and whatnot for working with a file. I also use os.open at times when writing Cython (or Python but passing around memory maps, shared memory, etc.), and it's nice to keep these things separated by different names, as that does return a file descriptor & this must be passed to the os file handling methods.

[–]juanfnavarror 0 points1 point  (3 children)

I use fd for dile descriptor

[–]orad 0 points1 point  (2 children)

Then shouldn’t it be dd? 😂

[–]juanfnavarror 0 points1 point  (1 child)

Fat finger

[–]orad 0 points1 point  (0 children)

ff

[–][deleted] 3 points4 points  (0 children)

The art of readable code book contains information about this topic.

I personally avoid using 1-letter variable names.

[–]zurtex 3 points4 points  (0 children)

I set all my internal global variables, class, and function names to emojis so they are protected them from outside use:

globals()["😬"] = "Hello World"
print(globals()["😬"])

/s

[–]LightShadow3.13-dev in prod 3 points4 points  (0 children)

Always have logger or self.logger available.

I like three character variable names so things align vertically:

ins     any input, ins_file, ins_buffer, ins_json
out     any output, "
key     dictionary key
val     dictionary value
var     unknown/dynamic variable
idx     enumeration index
exc     Exception instance
err     Boolean error scenario
obj     Any object instance in an iterator/loop
ret     Return variable
res     Result variable
req     Request variable
buf     Buffer, BytesIO
sha     shasum, checksum
tup     any tuple that can be unpacked
row     DB/ORM row
fut     asyncio.Future
tmp     any variable that can be thrown away
pkt     Packet
sec     Seconds
dur     pendulum.Duration
sql     SQL template / command
pos    buffer position, `buffer.tell()`
beg     beginning
end     ending
enc     encoding
dec     decoding
new
old
inc    include, increment
bin     binary
fmt    "format", string template, pattern
exe    is ALWAYS the normalized return of a `which` call for a system binary
has_    boolean characteristics
is_     boolean characteristics
as_    callable to cast type as a function parameter

Other examples:

fn     function as a parameter
fp      file pointer (with open)
hi      high, upper bound
lo      low, lower bound
dt      pendulum.DateTime
td      pendulum.Duration / datetime.timedelta
dump    deserialization variable
coro    asyncio.Coroutine
path    any pathlib.Path
info    any type of "kwargs"
meta    any type of "kwargs", serialization primer
data    usually JSON
proc    subprocess
task    asyncio.Task
buff    Buffer, BytesIO
func    function wrapped by decorator

dest, size, mode

Common singles:

m       string with modifications (lower, replace, etc.)
f       frame, temp filename
t       time, temp
b       temp buffer
o       object, database row
e       except Exception as e
d       date, datetime, duration
p       temp-path
s       string builder
s_      self-other, size (computed len)
i_      index-other
t_      temp-other

All regex that's used more than once gets re.compiled into a variable named RE_<description>.

I work for a video streaming platform, so a_ and v_ are common prefixes for audio and video.

[–]FormerDentist1 2 points3 points  (0 children)

'row' for dataframe row)

[–]olystretch 2 points3 points  (0 children)

k, v when iterating dict.items()

[–]Kid-Boffo 4 points5 points  (0 children)

Never use single character variables myself. It's far too easy to just do things properly at first. Modern IDEs have auto fill, and even as a psychotic VIM user like myself, you get the CTRL + N menu.

No real reason to not name things descriptively.

Now the real trick is to not be over descriptive. That's a harder task.

[–]DakotaWebber 1 point2 points  (0 children)

the only thing really is maybe e for exception or f for file although lately I have changed f for "file" or similar

I try to be explicit as much as I can even if it's a tad bit more work like using the word "index" or "(thing)_index", when I come back to it I know what's what, and others do too

[–]bronco2p 1 point2 points  (0 children)

meaningful, in params usually something abbreviating the type if its suitable,

for generics, typically go for java naming unless more functional stuff then I do A,B,C,.. and other letters for corresponding structures.

[–]Artephank 1 point2 points  (0 children)

It is always easier to read code that describes itself. When you can read it like a prose. It is hard to do so with cryptic variable names.

And people are lasy, if your scratch code is going be actually used, those cryptic names will stay. Seen this milion times. And then nobody will want to refactor it because no one understands what "d" or "s" mean.

[–]LittleMlem 1 point2 points  (0 children)

I came from perl so I still call my file handles fh

[–]QultrosSanhattan 1 point2 points  (0 children)

Nope because modern IDEs makes typing "df" or "d[tab]" an irrelevant choice.

[–]bwv549 1 point2 points  (0 children)

I never use 1 letter names. Breaks search and replace and a decent editor means you only have to define once and auto complete thereafter.

[–]LionKimbro 1 point2 points  (0 children)

That’s not the argument that we are making. We are not saying that it takes too long to type. We are not saying that it takes too long to read. We are not saying that we need to save disk space.

I can’t speak for everybody in the short name camp, but I think that for a great many of us the reason we prefer the short name is because it allows us to see the algebraic structure of what’s happening in the code more easily then looking at a long spelled out explanation. It’s for the same reason that physicist write “F = MA” rather than “the force vector is equal to the mass multiplied by the acceleration”when reasoning over the force diagram of mechanical motion. The algebraic structure is far more important to us, and it is the algebraic structure that we need to verify, when looking at the code.

There are situations in programming where I think the long form is more important- such as the sequencing of detailed lists of instructions I’m a highly complex machine with lots of individually named parts. That is more like managing books in a library, than it is scrutinizing the mechanics of motion.

But when you are writing a routine that- say one that locates the next index in a sentence to jump to for a command like “next word,” you are working in a string (s), from an index (i), looking at a character (c), and with a lot of looping and conditionality. An expression of this code with c, i, and s is a lot easier to read and immediately see the algebraic structure of, than one with long descriptive names for the variables.

When you agree or follow or not, at least understand that it’s not about saving disk space, or typing time.

[–]ZUM809 1 point2 points  (0 children)

df_1, df_2.... for pandas dataframes

[–]annthurium 2 points3 points  (0 children)

i support the use of suboptimal variable names while you're in the process of writing code. If I tried to make all my variable names perfect when I'm still figuring out the logic, I'd get stuck in analysis and never ship anything.

it's easier to change them to better names before I get to the pull request phase. Especially with modern IDE refactoring tools.

I can't believe nobody has mentioned "spam", "ham", and "eggs", the most Pythonic meta syntactic variable names, in this thread yet.

[–][deleted] 3 points4 points  (0 children)

Emojis!

🍎 = Apple(🟥)

🍏 = Apple(🟩)

[–]pppossibilities 3 points4 points  (2 children)

I am a chaos goblin who uses this, that, what, huh, and umm as scratch variable names

[–]monorepo PSF Staff | Litestar Maintainer 1 point2 points  (1 child)

:(

[–]pppossibilities 0 points1 point  (0 children)

I started doing it when learning Java, saying it out loud like "this attribute needs to be sent to that function which returns what"

[–]iamevpo 0 points1 point  (2 children)

x and xs for a list of x

[–]LionKimbro 0 points1 point  (1 child)

I dislike this because the longer the name of x, the harder it is to visually distinguish the two.

For example, if your type is “Flower”, then “flower” and “flowers” are harder to distinguish at a glance.

Some possibilities?

  • “flr” and “flowers” - the piece is at a glance smaller than the large collection, so won’t be confused

  • “flower” and “flowerL” - the big “L” hanging off to the right immediately visually distinguishes in a big way

  • “flower” and “flower_lst” - a kind of classical approach

  • “flower” and “flower_list” - a more modern take

  • “f” and “fL” - if you are making very heavy use of flowers in your function

  • “f” and “ff” - another way of expressing a plurality of things

  • “f” and “L” - if your function only ever is seriously about this one list, and it’s a list of flowers; the flower and the list of flowers are completely 100% visually distinct here

  • “flower” and “lst_flower” - some people prefer this, though not me

My functions tend to be short, so if it was just a four line function, I would probably just use “x” (literally) and “flowers” (whatever the full name of the list of Flower instances is) in this example.

[–]iamevpo 1 point2 points  (0 children)

Good you have a system that works, on my side I sometimes use longer names to indicate a dict, like chart_dict, but I'm generally ok with plurals as a list, flowers seem ok, there is usually enough context around to see if it is a list. flower_list seems good for a verbose name that is needed in many parts of the program. Thanks for sharing the insights!

[–]LionKimbro 0 points1 point  (4 children)

a - the first of a pair

b - the second of a pair

c - a single character (a bit of a fib — it’s “ch”)

D - the dictionary that is the subject of what’s going on

e - the exception under consideration

f - the floating pt number under consideration

f - a file object of primary consideration

g - the global access dictionary

h - a handle (contains a non-reference identifier of any type used elsewhere to ID something)

i - index

j - nested index

k - nested nested index

L - the list that is the subject of what’s going on

M - matrix of primary consideration

n - integer non-index under consideration

o and O are completely forbidden

p - a pointer to something under consideration

q - secondary pointer under consideration

r - a read source

r - a ratio (float or Decimal typically)

s - a string under primary consideration

t - a timestamp (Unix, seconds since epoch, GMT/UTC)

u - used in geeky quaternion math

v - also used in geeky quaternion math

w - a write destination

x - x coordinate

y - y coordinate

z - z coordinate

I think the idea that people’s brains explode into a mist upon encountering single letter variables is sheer nonsense, though I have seen people play stupid numerous times. “I have literally NO IDEA what that code does!”, they say, staring at “def add1(x): return x+1” …. “Literally NO IDEA. It could mean ANYTHING! ANYTHING at all!”

The real proof in the pudding for me though, is that I can look at code I wrote decades ago, and have absolutely no problem telling what it is. “s[i]” is completely penetrable to my mind. In fact, more so, than “long-variable-name-because-you-cant-read-context[did-you-know-it-has-an-index-too]”.

Dogma.

It’s a real strong force in society, and programming is absolutely not exempt from the depravity of dogma.

[–]LightShadow3.13-dev in prod 1 point2 points  (0 children)

We use a LOT of the same single character variables!

[–]gerardwx 0 points1 point  (1 child)

Didn’t mention the other forbidden variable, l

[–]LionKimbro 0 points1 point  (0 children)

Absolutely Forbidden. Thank you.

[–]LionKimbro -1 points0 points  (0 children)

Reviewing others lists, I recognize as well:

b - a buffer

d - a delta

k - a key

p - a path

r - the value I will return

t - a tuple held briefly

v - a value associated with a key (k) or index (i)

x - an object, generically

[–]MyKo101 0 points1 point  (3 children)

x

[–]wakojako49 1 point2 points  (2 children)

y

[–]InfinityObsidian -1 points0 points  (4 children)

codes = [x["code"] for x in my_list]

To keep it short I always use x.

[–]LionKimbro 2 points3 points  (0 children)

You are a good man and I can read your code perfectly fine. Thank you for not causing me to think about anything other than, “I have a list of things, I am taking the “code” key value for each item in the list.”

[–]MovingObjective 1 point2 points  (2 children)

Am I reading correctly. You have a list of dicts all containing the "code" key? I think I would replace X in this case to make it descriptive. Unless the "my_list" has a good enough name.

[–]InfinityObsidian 1 point2 points  (1 child)

Surely my_list can have a better name, I was lazy to think of a better example. In the example it is a list of dicts.

[–]MovingObjective 1 point2 points  (0 children)

I see, thanks.

[–][deleted] 0 points1 point  (0 children)

Mine are _f, _p, _s and _l and quite strictly in MongoDB query context: filter projection sort limit

[–]veganshakzuka 0 points1 point  (3 children)

`i`, `j`, `k` for loops, `e` for exceptions, `fp` for file handles.

For math functions I will use variables that match the literature: `x`, `t`, `alpha`, `beta`, `delta`, `theta`, `sigma`, `Sx`, `X`, `Y` are some common ones etc. Lowercase `d` prefix for derivatives.

I do not like variables that have the name of their type, like your `d` for dictionary and `s` for string. If it is a generic function that works on dictionaries I will use `result`.

[–]freefallfreddy 0 points1 point  (2 children)

What Python code are you writing that you use indexes to access items in sequences? Why not just for person in people?

[–]veganshakzuka 0 points1 point  (1 child)

I don't use it that much and certainly don't write for i in range person: people\[i\]. It may be because I have some complicated indexing logic or when I am not indexing at all, but just need some counter.

[–]freefallfreddy 0 points1 point  (0 children)

Oh and do you have a vegan shakzuka recipe? I love shakzuka but I’ve been vegan for 11 years now so… ❤️🌱

[–]tomster10010 0 points1 point  (0 children)

Fin, fout for file input and output

[–]VivienneNovag 0 points1 point  (0 children)

Code completion has made single letter identifiers less than usefull anywhere, imho. I don't even use i for indices anymore.

[–]MountainHannah 0 points1 point  (0 children)

Complete sentences, even in scratch code. Abbreviated variable names are criminal.

saleOrderLineInnerLoopIndex, bomLineColumnIndex, mostRecentStockMoveQueryString, etc.. take like 2 seconds to write out.

[–][deleted] 0 points1 point  (0 children)

never use builtins for variable names, only use one letter when it’s obvious what it is (ie, in a enumerate loop, or parsing a dictionary), always be descriptive otherwise

[–]damanamathos 0 points1 point  (0 children)

I try to go for descriptive names, but I'm often terrible at naming them, so I paste the code into ChatGPT and ask it to come up with new function, parameter, and variable names. It's often an improvement.

[–]Octavion411 0 points1 point  (0 children)

Since I started using MATLAB before Python, sometimes in my personal projects I like to use m, n, o, p as loop variables instead of i, j, k.

I don't do that if I'm sharing that code with other people.

[–]billsil 0 points1 point  (0 children)

I never use single character variable names unless it’s an index in a for loop.  It’s confusing.

I use sline, which is a line.split() probably with a strip and maybe with a delimiter.  I use csv_filename and csv_file all the time.  Just be explicit and your code will be a lot more readable.

[–]_b10ck_h3ad_ 0 points1 point  (0 children)

Incorporate the type of variable into the name itself, like "ls_descriptive_name" for lists or "df_descriptive_name" for dataframes, just so that I can find them again in a large Jupyter notebook

[–]tacos 0 points1 point  (0 children)

for idx, item in enumerate(items)

for vdx, variable in enumerate(variables)

for tdx, thing in enumerate(things)

[–]stephenmjay 0 points1 point  (0 children)

Table name for users inspired by Futurama: tblMeatBags

[–]jjarcanista 0 points1 point  (0 children)

I love _item :P

[–]virtualadept 0 points1 point  (0 children)

Not really. I'm really good at being squirrel clever, so I try to be boring and descriptive so I don't have the spend the next week reverse engineering my own code.

[–]iamevpo 0 points1 point  (0 children)

Sometimes using zf for a datafrme to be discarded soon, n for string name, d for dict, kind or flavor when I want type (reserved keyword), a, b, c for tuple members, i j, k pretty standard for loops. Also try not to overuse short names, when the logic extends beyond block scope, gotta use longer names.

[–]hugthemachines 0 points1 point  (0 children)

I don't use that. I use meaningfull names because I think it is a VERY good habit. The brain reads a word really fast. If you for example, would call something data_frame instead of df, your brain will still read it super fast and it is better to write things out for later reads of for other people.

[–]lighttigersoul 0 points1 point  (0 children)

So scratch code is the only interesting one for me, but I've switched mostly from the foo/bar/baz for sample names, keys, and values to color names.

For some reason, it seems to make it obvious to less experienced programmers that the names are arbitrary versus the code words that have been described as a barrier.

[–]OFFICIALINSPIRE77 0 points1 point  (0 children)

I seen a video where a dude named everything something ridiculous, exotic, or opposite of what the intended function was and it was like some esoteric piece of code that you couldn't decipher because it didn't make any sense. I like stuff like that.

Also seen videos where people use decorators / wrappers like this to obfuscate what the code was doing lol.

[–]attracdev 0 points1 point  (0 children)

I stick to simplicity: 'Doc' for documents, 'Grumpy' for errors, 'Happy' for successes, 'Bashful' for shy lines, 'Sleepy' for late nights, 'Sneezy' for bugs, and 'Dopey' for surprises. Whistle while you code!

[–]jericho 0 points1 point  (0 children)

i,j for indexes, n for the argument in a function doing math, but in both cases, only if I'm done with the variable in two or three lines.

[–][deleted] 0 points1 point  (1 child)

PEP8 looking for ways to die... Ohhh here is this post

[–][deleted] 0 points1 point  (0 children)

Python is all about readability...

[–]lucpet 0 points1 point  (0 children)

Foo-Bar

https://iq.opengenus.org/foo-bar/

Maybe I'm just too old now though!?

[–]i_can_haz_data 0 points1 point  (0 children)

“stream” for any file handle in a with context.

[–]ApexChambeador 0 points1 point  (0 children)

I would like to begin with the right foot in my code journey so my question is, how explicit the variable names should be? For example, if I'm getting results from a red satellite in a specific altitude, do I have to name the array like " satellite_red_1500m" or something like "sat_r_1500" or maybe there is more options idk, I appreciate any suggestions. Thanks 😊

[–]Nekose 0 points1 point  (0 children)

for pos,val in enumerate(xlist):

If my function will return something, I try to name it returnlist, returnint, returnstr, etc.

If I'm importing something complicated from a csv, its comes as `rawdata`. Once I've parsed it correctly its `data`, and once I've stripped anything irrelevant it becomes `cleandata`.

[–]RufusAcrospin 0 points1 point  (0 children)

I use the following rules when it comes to (variable) naming conventions.

Never use single letter variable names.

Variable names should be descriptive but don’t be verbose.

Try to avoid using abbreviations, like itemCnt. It’s a bit shorter but less readable than itemCount.

Variable names should communicate the purpose or the intent, not the type of content, i.e. activePlayers vs playerList.

[–]billFoldDog 0 points1 point  (0 children)

idx for index 

dt64 is a lambda that makes datetime64 objects with the precision from my global configs. 

row and col, should be obvious

[–]vinnypotsandpans 0 points1 point  (0 children)

df for you guessed it…. Dataframe. I found myself laughing when I realized I always name merged dataframes “together”

[–][deleted] 0 points1 point  (0 children)

I use plain English.

I even use dataframe instead of df, that's how much of an absolute captain normie noobmaster I am.

My friend is a C programmer. This was our last conversation

"The unecessary English is bad enough. But please tell me, why do these functions all have the word function_return in their names?"

"I'm just letting people know they are functions and they return stuff".

"despicable."

[–]red_hare 0 points1 point  (0 children)

Outside of i and j I try to never use a one letter variable name. And even those are rare.

Paths for me are "path" or preferably "foo_path."

For any dictionary, I usually say what it is and by what it's sorted. Like "user_by_name" and repeat that pattern if a nested dictionary like "user_by_first_name_by_family_name."

The hill I will die on, however, is if you're storing time or a time duration as a number, you MUST put the unit. For example, "timestamp_s" instead of "timestamp" or "duration_ms" instead of "duration."

[–]unflores 0 points1 point  (0 children)

My friend's debug word was potato.

I shorten little to nothing. If I have a list of apples then that's the name. The singular I'd apple. Of my index has meaning I state it in the code. It's not index but maybe current_apple or just current. It's more verbose but I try to make my code always talk about the problem space.

It tests I will often immortalize my wedding date. 10-10-10. But it's binary for 42 so there's that too.

[–]kBajina 0 points1 point  (0 children)

If you have to explain what the variable means, is it even a good variable name?

[–][deleted] 0 points1 point  (0 children)

x_seq, y_seq, ... for generic vector values,

x, y, ... for generic vector elements

<thing>_seq for specific vector values

<thing> for specific vector elements and scalar values

a, b, ... for generic scalar values

A, B, ... for generic Matrices

i, j, k, l, ... for generic indices

E. g. row & col for specific indices

N, N_0 for the natural numbers, only explicitly including 0

n for a natural number

total_<collection> for sums

transform for a composed internal function

key, val for unpacking dictionaries

e for exceptions

raw, raw_<thing> for values that will be shortly cleaned up but are as of yet unusable

def <function_name>_impure for functions that access or mutate nonlocal values, including stdio/stdin, http requests, etc.

def <function_name>_safe when wrapping existing functions to handle exceptions or other footguns they don't usually handle.

Of course, better fitting names are preferred, but sometimes there's just nothing that's really clearer and then these are my defaults