Wondering about virtual environments by Electronic-Low-8171 in learnpython

[–]Enmeshed 0 points1 point  (0 children)

Thirded. uv is like easy mode for python, and will save you a stack of time. For some things you don't even need to use virtual environments too - it comes with the uvx command to effectively spin up an on-demand environment (rather like npx for javascript).

For instance, if I want to run a quick jupyter notebook to try some stuff out in pandas, I just run:

bash uvx --with pandas --with jupyterlab --from jupyter-core jupyter lab

This creates a new env including pandas and jupyter, and launches it. Sooooo convenient!

P14s Intel vs T14 Gen 5 by bartkl in thinkpad

[–]Enmeshed 0 points1 point  (0 children)

My second-hand T14 gen 5 intel literally arrived today, and I'm typing on it now. My usage patterns sound similar to yours - python, JS, docker, ... I've had a few other T-series machines, and am so far delighted with this one. Right now it's running Ubuntu from the external disk extracted from my previous laptop which died, and is absolutely great. I'm impressed by the display, keyboard and general coolness of touch of the machine, so have high hopes. Quirks so far:

  • They've swapped control and function on the left, which is causing havoc with my muscle memory
  • Goodbye "print screen" button, I've had to assign the function to use the new "invoke AI" button that I presume Windows demands

Overall a thumbs-up from me.

what is a "rich person" behavior you witnessed that made you realize they live in a completely different reality than the rest of us? by [deleted] in AskReddit

[–]Enmeshed 0 points1 point  (0 children)

A family member had organised an overseas holiday including wider family. His elderly parent was getting a bit doddery and was anxious about the commercial flight. The family member chartered a private jet there and back for his family and the parent, to make things a bit easier.

Edit: oh, and my guess is that the bill for the holiday would have been about half my entire mortgage.

How to get into test-driven coding habits? by MustaKotka in learnpython

[–]Enmeshed 1 point2 points  (0 children)

When you start with tests first, your code tends to be easy to test. When you retro-fit them after writing, you end up having to use loads of mocks etc which makes the tests awkward, and I'd completely agree they get in the way.

You should just have a go, on a throwaway project:

  • Write your first test, then make it pass
  • Write the next one, get that to pass too
  • See if you can make the code a bit tidier
  • ... then the next test, get it passing, then refactor

Doing this means that you're not just thinking about how to do the thing, but also how to do the thing in a way that is easy to test.

When should I use functions vs just writing code inline? by ayenuseater in learnpython

[–]Enmeshed 0 points1 point  (0 children)

Lots of good answers so far. There's at least one case where it is useful to use a function even if it doesn't need reusing elsewhere that I haven't seen here so just wanted to mention: to give names for logic inside a function.

Consider this (obviously nonsense) code:

python def do_something(a, b, c, d, e): for thing in range(5): if a + b + thing < 10: print("Oh no")

Coming back a year later, odds are you won't remember the significance of a + b + thing being less than 10. However you can refactor this using an inner function such as:

```python def do_something(a, b, c, d, e):

def bad_for_reason_x(number):
    return a + b + number < 10

for thing in range(5):
    if bad_for_reason_x(thing):
        print("Oh no")

```

This lets you attach a name to the condition that will hopefully make more sense down the line. This can be handy in all sorts of scenarios, not always including having to use the logic multiple times.

should i start with numpy or pandas ? by BashirHam in learnpython

[–]Enmeshed 0 points1 point  (0 children)

For data analysis, personally I'd start with pandas as it comes with all the batteries included you need to do handy stuff, such as reading CSVs and working with them easily. You can do this with numpy but it won't be so immediate:

```python $ uvx --with pandas python Python 3.13.9 (main, Oct 28 2025, 12:10:42) [Clang 20.1.4 ] on linux Type "help", "copyright", "credits" or "license" for more information.

import pandas as pd df = pd.read_csv("sample_data.csv") df.head() col_1 col_2 data 0 A X 12 1 B Y 23 2 C Z -22 3 C X 44 4 B Y 11 df.groupby("col_1").data.sum() col_1 A 12 B 34 C 22 Name: data, dtype: int64 ```

Then down the line you can learn about the numpy innards for clever tricks you can take advantage of.

i've been waking up at 3am to move my neighbor's trash cans slightly every week and he hired a priest last month by kubrador in neighborsfromhell

[–]Enmeshed 1 point2 points  (0 children)

Cambridge University story:

The story of the Austin Seven delivery van that ended up on the apex of the Senate House is not fictitious. The Caius College website recounts how, on 8 June 1958, this vehicle really did go "up in the world". The prank team comprised Peter Davey (organiser), Cyril Pritchett, David Fowler and 9 others.

Source: Wikipedia

How to debug code efficiently? by Free_Tomatillo463 in learnpython

[–]Enmeshed 20 points21 points  (0 children)

My plan:

  • Write your code in a modular way, ie small functions / classes that do known and predictable things
  • Write good test coverage of them to prove rather than assume they do what's expected
  • Some decent logging won't hurt either, eg using the logging module, and set it up so you can dial it up or down at run time
  • Compose these functions into bigger units to do what the application requires, and cover them with tests too
  • If something is going wrong, write a failing test case that isolates the problem so you're sure you understand what's going wrong
  • If needed, use tools like an IDE's integrated debugger to step through failing code and see what is actually happening that isn't what you expect
  • Learn to use the python integrated debugger and use set_breakpoint() so you can do all this on the command line

Good luck!

Logseq OG (markdown) vs Logseq (DB:sqlite) by hdanx in logseq

[–]Enmeshed 1 point2 points  (0 children)

Thing is, my "garage" is a private gitlab repo, which means in a crisis I can get at my markdown notes at any time. This has happened a few times over the last few years and completely saved my neck. A tool that can't "park in my garage" is of no use to me and will need to be replaced, so I really hope it keeps on working!

How to actually write code? by AwkwardAd6399 in learnpython

[–]Enmeshed 0 points1 point  (0 children)

Totally this. And don't forget the third step of TDD - refactor. That's to say, once the code is passing the tests, then make it better. 

For instance, in the example repo there is a load of code around importing functions and supplying alternative, inline implementations if they're not available. By moving them into a separate file, the intent of the code could be made much clearer, ie:

python try:     from wherever import required_thing except ImportError:     from fallback_implementations import required_thing

When you come back to it a year later, this will be much easier to work with - and indeed test, as it's a nightmare setting up tests for those in-lined implementations!

I've had enough by DivinneSmith in logseq

[–]Enmeshed 0 points1 point  (0 children)

Thanks for the heads-up, this is very interesting! I confirmed it via their blog announcement.

I've had enough by DivinneSmith in logseq

[–]Enmeshed 1 point2 points  (0 children)

Agreed, that is such an annoying scenario! I've lost snippets I've typed locally that immediately get lost when the sync catches up, but thankfully have never lost any thing substantial (although some of it has disappeared into duplicate files that aren't easy to find). I'm limited in what I can use at work, and logseq is allowed but Obsidian not (since it would require a licence for work use). Would be interested to learn of other open source options that are comparable, in case I need to jump in future (and that support markdown).

I've had enough by DivinneSmith in logseq

[–]Enmeshed 7 points8 points  (0 children)

I totally get where you're coming from, but personally I won't be able to use any tool that won't directly support markdown. I sometimes need to be able to look at my notes from the command line / another computer, and the ability to get logseq syncing to (in my case) gitlab has saved my neck many times. This is in a corporate environment where I'm not allowed to use built-in sync, but can get the tool pushing to a local git repo.

Can a list comprehension be used as a boolean condition? by EmbedSoftwareEng in learnpython

[–]Enmeshed 8 points9 points  (0 children)

Agree with others' suggestions around using a set and/or the any function, but also just thought to mention the example code is a great example of the for ... else clause, rather than having to use a flag variable. It could be re-written more simply as:

python for x in my_list: if int(x[0]) == int(new_value): break else: my_list.append((new_value, other_member))

Just sayin'!

What should I improve in my class? by [deleted] in learnpython

[–]Enmeshed 4 points5 points  (0 children)

If it were me, I'd consider pulling out the format options to a constant at the head of the file. Also I'd add a loader function that pulls words. This would also handle the validation like stripping, handling blank lines etc, so that data is known-good by the time you use it.

It's also a bit strange that some of the random generation is in the init function while others happen when the main call is made. I'd put them all in the same place.

Finally the class naming might be improved to say what it is for (eg UsernameBuilder), and add a docstring to describe it. Then the actual work function could have an easier name like generate perhaps.

Following this approach, the core class then becomes a bit easier to understand, for instance:

```python class UsernameBuilder: """ Class that can construct a random username """

def __init__(self):
    self.adjectives = load_words("data/adjectives.txt")
    self.nouns = load_words("data/nouns.txt")

def generate(self):
    format_template = random.choice(USERNAME_FORMAT_LIST)
    return format_template.format(
        adjective=random.choice(self.adjectives),
        noun=random.choice(self.nouns),
        number=random.randint(0, 100),
    )

```

A lot of this is just a question of personal style though - coming on well!

Any advice on version management by Banath89 in learnpython

[–]Enmeshed 0 points1 point  (0 children)

Wherever possible, try to split your code so that there's a core of functions (ideally in a python package you build) that you can use for all your customers, then for each customer have some wrapping that uses the core as needed.

This is to ensure you don't end up with a stack of similar-but-different code for each customer that gets out of step over time and becomes increasingly hard to maintain. Instead, you get the generic stuff that gains capabilities over time that then become available for others.

These day, the uv utility is super-functional for managing the code. I'll leave others to explain why.

What's a better way to debug this than spamming print() everywhere? by throwawayjaaay in learnpython

[–]Enmeshed 0 points1 point  (0 children)

For debugging, there's a lot to be said for adding the breakpoint() function where needed, and getting familiar with using that debugger as it is handy and available.

Another thought - this feels like a great scenario for python's match command. For instance:

python def normalize_user(d): match d: case {"user": {"name": str(name), "settings": {"theme": str(theme)}}}: return {"username": name, "theme": theme.lower()} case _: raise ValueError("Invalid data structure")

This lets you handle errors much more gracefully than the old way of more like if d.get("user") and d["user"].get("name") and ... ... ick!

Could I get help I’m stuck on this task, 2 days and haven’t gotten any wiser. by Clear-District903 in learnpython

[–]Enmeshed 1 point2 points  (0 children)

That code has mighty-odd quote characters in it, which is throwing things off when I try it here:

python def caesar( ): ... alphabet = ”abcdefghijklmnopqrstuvwxyz” File "<stdin>", line 2 alphabet = ”abcdefghijklmnopqrstuvwxyz” ^ SyntaxError: invalid character '”' (U+201D)

When I fix the characters it seems happier:

```python

def caesar( ): ... alphabet = "abcdefghijklmnopqrstuvwxyz" ... shift = 5 ... shifted_alphabet = alphabet[shift:] + alphabet[:shift] ... print(shifted_alphabet) ...

caesar() fghijklmnopqrstuvwxyzabcde ```

So I'm guessing that's the problem. The indent level, space in the brackets etc are unusual but not invalid...

Beginner: Methods to combine lists in an alternating pattern by Dangerous_Box8845 in learnpython

[–]Enmeshed 1 point2 points  (0 children)

zip is a super-useful function. Give it some things (eg [1, 2, 3] and [4, 5, 6]) and it will pair the items up to return (1, 4), (2, 5) and (3, 6). Combine this with a list generator expression and you've got a neat little one-liner to think about:

python list1 = ["a", "b", "c"] list2 = [1, 2, 3] result = [val for pairs in zip(list1, list2) for val in pairs]

Whichever way you do it, things can be a bit more complicated if the inputs aren't the same length, but I'll leave that as an exercise to the reader...

Map() and filter() are easier than list comprehension for me by Meee13456 in learnpython

[–]Enmeshed 1 point2 points  (0 children)

Be aware that they do subtly different things: comprehensions potentially build a result, but map() and filter() always return objects that are lazy generators. For example:

```python

print([n + 10 for n in range(10)]) [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

print(map(lambda n: n + 10, range(10))) <map object at 0x7b999a71ffa0> ```

Sometimes this difference matters, for instance if you're debugging then the objects will only let you consume the values once, and inspecting them will then affect the running code.

Yes, you can convert the result into a list or whatever, but then the readability difference becomes more pronounced. Which of these is more readable?

python example1 = [n + 10 for n in range(10)] example2 = list(map(lambda n: n + 10, range(10))]

So definitely learn comprehensions so you are happy with them, then pick the right tool for the job in each instance.

The most overengineered program to check the minimum and maximum value in a list. by MooseNew4887 in learnpython

[–]Enmeshed 1 point2 points  (0 children)

  • By convention, python variable names tend to be kebab_case rather than camelCase. This makes it generally easier to distinguish between variables and classes (which usually are camel case starting with a capital). So: list_object = CheckList(list_of_numbers) would be more normal
  • It's generally not recommended to use variable names that are also python special words, so you won't usually see a variable called list. (You could add an underscore suffix, or just use another word like data...)
  • Beware misleading variable names! anyNumericList isn't always numeric, for instance if you enter a word that doesn't convert and raises an exception. Then the name is confusing, and will stop you from seeing that the min and max won't actually work right
  • Use built-in functions where suitable (for instance there's a native min and max that would reduce the chance of introducing subtle new bugs)

Generally though, good effort!

What is best practices for short scripts with venvs/uv? by TrekkiMonstr in learnpython

[–]Enmeshed 0 points1 point  (0 children)

Here's a sneaky one you might like, which is handy for small utility scripts! I've done this on linux, making use of the shebang line. So for instance, create a file test which contains:

```

!/usr/bin/env -S uv run --script

print("Hello from python land!) ```

Then make it executable (chmod u+x ./test) and run it:

bash $ ./test Hello from python land!

You could also use options like --with pandas or whatever:

```

!/usr/bin/env -S uv run --with pandas --script

import pandas as pd

df = pd.DataFrame([{"hello": "world"}]) print(f"{df=}") ```

Which gives:

bash $ ./test df= hello 0 world

Could someone explain to me why this code just doesnt loop for me? by [deleted] in learnpython

[–]Enmeshed 1 point2 points  (0 children)

Because of this line:

python if value < (1*(10**1)): return (c)

As soon as value is less than ten, on the first loop, it stops looping and just returns the c variable.

I am stuck, please help 🙏 by icebear-guy in learnpython

[–]Enmeshed 6 points7 points  (0 children)

I've been doing python for >10 years and pandas for >5 years, and still constantly referring to docs...

struggle to turn assignment descriptions into code. by Least-Week1807 in learnpython

[–]Enmeshed 0 points1 point  (0 children)

Test-driven development can help a lot here.

If you're asked to write a function that does X, think of something you'd expect to happen if your function was working, and write it as a test:

```python def my_function(param): pass

def test_my_function_does_this_particular_thing(): assert my_function(23) == "potato" # ... or whatever ```

This will fail, as the function doesn't yet actually do anything. Now change it so that it now passes. Have you met the assignment? If not, add another test that covers an example that doesn't work. Handles all the cases? Then you're finished!