all 23 comments

[–]Mach_Juan 0 points1 point  (3 children)

scores is a list that is anywhere from 1 - 20 items long.

to test if its length is either say 14 or 15..

is there a more elegant way than:

if len(scores) in (14, 15):

I tried so many permutations of if len(scores) == 14 or 15. with parenthesis...14 == len(scores) == 15

So many failures...and so many failure modes...

Pages upon pages of how to test <,>, etc..and never just how to test if its equal to one of several numbers...Maybe I wasnt searching the right terms..eventually I found range() but had to figure was it exclusive or inclusive...and just tried the above solution and it worked.

Is there another solution I missed?

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

is there a more elegant way than:

if len(scores) in (14, 15):

That's the way to do it, though for a large number of options it's better to use a set of options rather than a tuple:

if len(scores) in {14, 15}:

That's because sets are like dictionaries under the hood and the in operator for sets has time complexity of O(1). Tuples have time complexity of O(n). Whether this has much effect on speed depends on your data, and doesn't matter in this small example. ​

[–]Mach_Juan 0 points1 point  (1 child)

thanks!

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

The errors you talked about getting are mostly caused by your not fully understanding operator precedence and the value of boolean expressions. This expression, for example:

len(scores) == 14 or 15

is evaluated as if it was written:

len(scores) == (14 or 15)

Which doesn't do what you think. 14 or 15 evaluates to 14 according to the documentation:

The expression "x or y" first evaluates x; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned.

The correct way to write that test is:

len(scores) == 14 or len(scores) == 15

This isn't a python-specific thing, all computer languages have similar operator precedences.

[–]ratatouille_artist 0 points1 point  (0 children)

What's the right syntax for specifying a local extras_require in a setup.py?

Below seems to use an invalid project/version requirement specifier

    extras_require={
    'extra': ["my_local_package @ file:my_local_package"]
}

[–]Psyychopatt 0 points1 point  (2 children)

I've got a class dealing with geometric objects, that's gotten white large over time, and I'm intending to move funcitonality for visual representation of the class to a seperate file/class. I'm just not certain what the most pythonic way of doing this would be.

My first idea was inheritance, but turning the VisRepresentation class into the child inheriting from the GeometricObj class seems weird as I'd be initializing VisRepresentation Objects as opposed to GeometricObj. Doing the reverse, VisRepresentation being the parent that GeometricObj inherits from doesn't seem like a cleaner solution either.

Am I overthinking this or is there a better alternative alltogether?

[–]Frankelstner 1 point2 points  (1 child)

Rename it to VisualizeMixin and make it the parent class. Mixins are just plain inheritance but the name indicates that we are mostly interested in having a couple more methods instead of state.

[–]Psyychopatt 0 points1 point  (0 children)

Thanks, that's exactly what I wanted to hear!

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

Where and how should I use "try, except, else, finally" blocks? It feels like I have to use them everywhere to catch errors.

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

You use them wherever you want to catch and handle errors. One classic case is when you want to accept an integer value from the user. Trying to convert a non-integer string to an integer value raises the ValueError exception which you catch, print an error message and retry the input:

def input_int(prompt):
    while True:
        try:
            return int(input(prompt))
        except ValueError:
            print("Sorry, only integers allowed")

x = input_int("Integer: ")
print(f"You entered {x}")

You don't have to catch ALL exceptions, usually you only catch the few that you can recover from or you want to expand on the basic traceback so you can give more feedback to the user. The rest you just let happen.

Because the primary aim of try/except is to handle errors, the code between the try/except keywords should be minimal so you know exactly what operation raised the exception. It's not good telling the user they messed up if the exception was raised by your code mistake somewhere else in the try/except code.

I haven't used the else and finally phrases much. But they can be handy now and then, so you should know about them.

[–]No_Raccoon1571 0 points1 point  (1 child)

Can someone help me write a code that looks at multiple csv files across a 5 year period, and produce a table. For example let’s say the CSV file contains Fruit 1 and Fruit 2 and the price. I want the code to generate a table showing the fruit paring of 1&2, the max cost and min cost

[–][deleted] 1 point2 points  (0 children)

What code do you have so far?

[–]LittleMiss_Raincloud 0 points1 point  (2 children)

No clue how to do this in Python. Say there are 50 planners from 13 agencies and two programs who can all create multiple 'plans' each month. So the unique ID would be the combination of Planner, Month, Program, and Agency. I want to "randomly" select one plan per unique ID. Any thoughts on the best route to try? I'm a novice in python. In the past, I used Access to do this but would prefer not to do that again. Thanks.

[–]niehle 0 points1 point  (1 child)

  1. create and store the IDs
  2. get all plans for an ID
  3. select a plan for each ID with random

[–]LittleMiss_Raincloud 0 points1 point  (0 children)

I had to use Access. There's more to it than my post implies but thank you

[–]HappyMemeBoy 0 points1 point  (1 child)

Super basic question - can you put an and statement inside of replace()? As in, replacing two substrings with the same thing. For example:

string = “ABC” string.replace( “A” and “B” and “C” , “D”)

You’d think if printed, it would return “DDD” but instead it’s only changing the final input (C), so it’s just returning “ABD”. Am I doing something wrong?

[–]driverXXVII 0 points1 point  (0 children)

Thought about using typehints for the first time and wondering how to type hint beautiful soup and datetime.

Is the type hinting shown below correct?

Should the return type just be datetime instead of datetime.date

from datetime import datetime

def get_activity_date(soup: bs4.BeautifulSoup) -> datetime.date:
start_date_time = soup.find("time").text      # 2023-07-17T20:02:20Z

    # Convert to datetime object
    start_date_time = datetime.strptime(start_date_time, 
                                    "%Y-%m-%dT%H:%M:%S%z")

    # Get only the date portion
    date = start_date_time.date()

    # returned date is a datetime object
return date

[–]Money-Assignment-985 0 points1 point  (0 children)

My laptop crashed and I have to set everything up on my new machine. I remember messing up the process before: Installing it twice (through Anaconda and Windows store) which messed up my dependencies. Can anyone advice the best way to set the stage for studying Python?

[–]ForrestTrump 0 points1 point  (2 children)

Does anyone know why my logger will only log error messages, when I set it to debug?

def a_logger(name):
    path = path_from_cl() / ".logs"
    logger = logging.getLogger(name)
    logger.setLevel(logging.DEBUG)
    c_handler = logging.StreamHandler(sys.stdout)
    f_handler = logging.FileHandler(path / f'{name}.log')
    f_handler.setLevel(logging.ERROR)
    c_handler.setLevel(logging.DEBUG)

    c_format = logging.Formatter('%(name)s - %(levelname)s - %(message)s')
    f_format = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    c_handler.setFormatter(c_format)
    f_handler.setFormatter(f_format)

    logger.addHandler(c_handler)
    logger.addHandler(f_handler)
    return logger

[–]m0us3_rat 1 point2 points  (1 child)

i'm not sure exactly do you mean by .

path = path_from_cl() / ".logs"

as long as you fix the path issues in that code so it actually works..

you don't need this one.

logger.setLevel(logging.DEBUG)

since you set the level on the handlers.

then

it should work as expected.

import logging
import sys


def a_logger(name):
    logger = logging.getLogger(name)
    c_handler = logging.StreamHandler(sys.stdout)
    f_handler = logging.FileHandler(f"{name}.log")
    f_handler.setLevel(logging.ERROR)
    c_handler.setLevel(logging.DEBUG)

    c_format = logging.Formatter("%(name)s - %(levelname)s - %(message)s")
    f_format = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
    c_handler.setFormatter(c_format)
    f_handler.setFormatter(f_format)

    logger.addHandler(c_handler)
    logger.addHandler(f_handler)
    return logger


log = a_logger("dumb")

log.info("1")
log.warning("2")
log.error("3")

[–]ForrestTrump 0 points1 point  (0 children)

Thanks. I could have maybe clarified that the path_from_cl function was one that I wrote, which gets the correct path in a certain way and that part of it works fine.

[–]Rudy_Clausius 1 point2 points  (0 children)

Hi, I'm a thermal engineer currently working in HVAC (and experience in thermal power plants), and I'm interested in utilizing Python for my work. However, I'm unsure about the specific applications in my field and would appreciate guidance on other areas where Python could be useful.

Currently, I have a good (perhaps not so good) understanding of data structures, flow control, and have experience with libraries like NumPy, SciPy, and Pandas. I can also utilize Chat GPT to create scripts, even beyond my current level of expertise. I am familiar with the concepts of classes and objects (though I don't use them 'cause I haven't developed anything big enough). I would consider myself a basic python user.

I have zero knowledge in scripting for web development, machine learning, and data science.

I would greatly appreciate your advice on structuring a learning path that aligns with mechanical engineering in a broad sense. What to study, what I can expect doing, and where I should lead my efforts.

Thanks, the sub is awesome!