sub
stringclasses
1 value
title
stringlengths
7
303
selftext
stringlengths
0
8.65k
upvote_ratio
float64
0.08
1
id
stringlengths
9
9
created_utc
float64
1.65B
1.65B
Python
I fixed python traceback real quick
​ https://preview.redd.it/yqvg54ml9sn81.png?width=2000&format=png&auto=webp&s=575484421b18464c240d3f384d3a1c7e3f4e3a34 yourprog = "whatever.py" from subprocess import check_output, STDOUT def abrT(r): return r o = "" # I don't care about unreadable code I am writing this during lunch break for line in r.split("\n"): if "Traceback" in line: o += "Traceback:\n\n" elif "File" in line: a = line[line.find(", ")+2:] + "\n" a = a.replace(", in <module>", "") o += " " + a elif ":" in line: o += "\n " + line.split(": ")[0] + ":\n " + line.split(": ")[1] + "\n" else: o += line + "\n" return o[:-1] result = str(check_output(f"python3 {yourprog}; echo -n", shell=1, stderr=STDOUT), 'utf-8') print(abrT(result))
0.69
t3_tfnswk
1,647,452,918
Python
Scrape Google Books in Python
This blog post uses [`parsel`](https://parsel.readthedocs.io/) as an HTML/XML parser that supports full XPath, instead of [`bs4`](https://www.crummy.com/software/BeautifulSoup/bs4/doc/). Shows how to scrape: - title - link - displayed link - snippet - author - publication date - thumbnail - preview, and more editions. If you need a step-by-step explanation, you can visit [Scrape Google Books in Python](https://serpapi.com/blog/scrape-google-books-in-python/) blog post at SerpApi, otherwise: ```python from parsel import Selector import requests, json, re params = { "q": "richard branson", "tbm": "bks", "gl": "us", "hl": "en" } headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.87 Safari/537.36", } html = requests.get("https://www.google.com/search", params=params, headers=headers, timeout=30) selector = Selector(text=html.text) books_results = [] # https://regex101.com/r/mapBs4/1 book_thumbnails = re.findall(r"s=\\'data:image/jpg;base64,(.*?)\\'", str(selector.css("script").getall()), re.DOTALL) for book_thumbnail, book_result in zip(book_thumbnails, selector.css(".Yr5TG")): title = book_result.css(".DKV0Md::text").get() link = book_result.css(".bHexk a::attr(href)").get() displayed_link = book_result.css(".tjvcx::text").get() snippet = book_result.css(".cmlJmd span::text").get() author = book_result.css(".fl span::text").get() author_link = f'https://www.google.com/search{book_result.css(".N96wpd .fl::attr(href)").get()}' date_published = book_result.css(".fl+ span::text").get() preview_link = book_result.css(".R1n8Q a.yKioRe:nth-child(1)::attr(href)").get() more_editions_link = book_result.css(".R1n8Q a.yKioRe:nth-child(2)::attr(href)").get() books_results.append({ "title": title, "link": link, "displayed_link": displayed_link, "snippet": snippet, "author": author, "author_link": author_link, "date_published": date_published, "preview_link": preview_link, "more_editions_link": f"https://www.google.com{more_editions_link}" if more_editions_link is not None else None, "thumbnail": bytes(bytes(book_thumbnail, "ascii").decode("unicode-escape"), "ascii").decode("unicode-escape") }) ```
0.5
t3_tfm16q
1,647,448,203
Python
OpenTelemetry and Distributed Tracing in Python - Introduction
0.33
t3_tflm99
1,647,447,107
Python
Add jemalloc to your Python Docker images
1
t3_tflf1p
1,647,446,556
Python
What's your favorite module/library/package?
Just wondering what's your favorite module and package which you like to use them? Mine is re. You can tell multiple, by the way.
0.5
t3_tfkh8z
1,647,445,189
Python
Writing production grade pandas with hamilton!
While Pandas is incredibly flexible and easy to get started with, it doesn't lend itself to writing good quality, extensible code. This is usually fine. Lots of it is thrown away -- written in notebooks and never seen again. However, a lot amount of it ends up making it into production ETLs, services, etc.. At Stitch Fix, we had a *lot* of monolithic, messy pandas scripts. We built [hamilton](https://github.com/stitchfix/hamilton/) to solve this problem. A programmer represents transforms on dataframes as a series of python functions. The parameter names are used to specify upstream dependencies, and the whole thing gets wired into a dependency graph. In short -- instead of writing: df['a'] = df['b'] + df['c'] You'd write: def a(b: pd.Series, c: pd.Series) -> pd.Series: return b+c Then you use a *driver* to customize execution, pass in paraemeters, etc... Note that its not at all limited to pandas -- while that was the initial use-case, it can handle any sort of python datatype! We've opened up this internal tool we're excited about to the outside world -- we'd love feedback, contribution, and use-cases! [https://github.com/stitchfix/hamilton/](https://github.com/stitchfix/hamilton/)
0.8
t3_tfkahz
1,647,444,723
Python
First time I used python
I'm coding with python for half a month now, in the beginning I was a bit sceptical what I would use it for but today I used it for the first time. To cure boredom, me and my friends are doing typeraces where we have to type as fast as possible. I'm pretty good at that but there is someone in my class that is just a little better. Its just because I type upper cases with shiftlock and she types with shift. So I wanted to learn to type with shift so I could type faster. But because I never did it that way I had to practice it so I wrote a little python program that generates a letter and then you have to type that letter. I was very happy how it turned out and I now I understand python can and will be very useful .
0.84
t3_tfiry5
1,647,440,485
Python
OPToggles - a feature flag Open Source project
Hey r/Python! Just wanted to share our open source project launching today. Thought some of you might find it useful, and we would love to hear your feedback. As devs, we often want our frontend to reflect the permissions enforced by the backend - i.e. if a user is not allowed to run the action behind a button - don't show the button. [OPToggles](https://github.com/permitio/OPToggles) uses[ Open Policy Agent](https://github.com/open-policy-agent/opa) to automatically enhance feature flag solutions by creating user-targeted feature flags. It already supports LaunchDarkly and a generic REST API.
0.76
t3_tfil3b
1,647,439,946
Python
How do you really share constants across your project in a Pythonic way?
Assuming i have a package i created who get input text, and return a huge dictionary with 50+ keys. Since *all other packages* in the program are using this dictionary and play with those keys, I don't want to hard code the keys, but keep them as global **constants**. So here are my options and i feel uncomfortable with both of them: 1. Put all constants vars in a separate folder/package in root folder, and *import them to each package* that use them. To my eyes it makes the code **hairy and uncapsulated.** I love the SW engineering where you have a package that depend on nothing outside. 2. Pass all arguments in this config package to *each* package who need it - which also make things ugly hairy and confusing, and require putting all constants in a class(there are no structures.) ​ I know that most people go with **1**, but my code has like 10+ packages i wrote, each package has multiple files, ***each*** depend on these constants(50+), and if i import the constants (even with **absolute import**) to each, it makes me feel uncomfortable. What if i want to give my package to another developer ? i need to gather all these dependencies? **How is this done in huge multi developers programs ?**
0.57
t3_tfhvue
1,647,437,921
Python
Import of modules is slowing down executable. Can it be imported locally or what can be done differently ?
I am importing the following modules/libraries which is causing the exe to take a few minutes to start. How can I store them locally or what can I do differently so that the exe starts quickly? When I run this from the Notebook it the application runs without any delay. I wonder if there is a way to speed up the exe. import time import openpyxl from os import path from selenium import webdriver from openpyxl.styles import Alignment from webdriver\_manager.chrome import ChromeDriverManager from openpyxl.styles.borders import Border, Side from selenium.webdriver.support.ui import Select import os import math import win32com.client as client from PIL import ImageGrab ​ Thank you in advance.
1
t3_tfh1l5
1,647,435,382
Python
Stylistic choice of validation functions
Hey all! Got a question. I’m working on a validation script for work verifying some supplied input against required values. I’m wondering, stylistically, if there’s a “preferred way” to write these functions. An example function… Def name_max_length(name): if 1 < len(name) <= 128: return None else: raise ValidationError(“Names length fell outside of max range.”) Apologies if Reddit mobile mangled that code but it’s short enough that I think everyone can still grok it. If you were working on a project would you want to see the above? Or would you rather read a single if statement, without an else, checking to see if it fell outside of the valid range and if so raise the exception. I thought PEP-8 had a stylistic recommendation about positive vs negative checking for if statements but I gave it a quick scan and didn’t see anything. I’m going to be writing a lot of these, so I’d like to get a solid stylistic choice under me. I’m also curious, would you rather see these ranges hard coded in the if statement, or see two local variables (min/max) and have “if”compare against those?
1
t3_tfgida
1,647,433,601
Python
what to do after practice python. org?
Helo I'm a beginner and I've finished the exercises from practice python org and I m clueless as to what my next step should be. What do you recommend, I tried advent of code but a lot of the exercises are way too hard for me. thanks very much
0.79
t3_tfflsy
1,647,430,590
Python
Create a hello world app using django
0.75
t3_tffh4r
1,647,430,119
Python
My first ever Python Project!! I named it tagSearch
I saw a twitter post the other day "Is there a tool that I can get meta tags off of a web site? I couldn't find any". I thought to myself, there probably is, but I should do one too for at least practice. So I made this small script called tagsearch, basically it collects wanted tags off a site. It can also scrape certain tags that have a wanted attribute, like span tags but only if they have class attr. I also added regex support meaning one can make regex search on the scraped tags. My GitHub repo: [https://github.com/teooman/tagsearch](https://github.com/teooman/tagsearch) Example image https://preview.redd.it/5ic7krt7aqn81.png?width=1419&format=png&auto=webp&s=afabf3817e73dc2075bbf2be6017c2bc76d36298 Any feedback would be highly appreciated!!
0.67
t3_tff544
1,647,428,851
Python
created a small utility to automatically activate Poetry virtualenvs when changing directories
[https://github.com/tvaintrob/auto-poetry-env](https://github.com/tvaintrob/auto-poetry-env) tested only on MacOS with zsh, heavily inspired by pyenv-venv's auto activation, please share any thoughts and suggestions!
0.75
t3_tfdemi
1,647,421,875
Python
GitHub - jamalex/notion-py: Unofficial Python API client for Notion.so
0.67
t3_tfcksk
1,647,418,317
Python
Which logic for if-else inside a function is better or more pythonic?
The logic between f1 and f2 is exactly the same, but the syntax is slightly different. This type of function shows up everywhere. Is one easier to read, or preferred in some way? Side note: I thought it was interesting that f2 is slightly faster than f1. import numpy as np arr = np.random.choice(['a','b','c'],100) def f1(cond): if cond == 'a': return 'a' if cond == 'b': return 'b' return 'c' def f2(cond): if cond == 'a': return 'a' elif cond == 'b': return 'b' else: return 'c' f1 timeit: In [1]: %%timeit ...: for i in arr: ...: f1(i) ...: 40.6 µs ± 804 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each) f2 timeit: In [2]: %%timeit ...: for i in arr: ...: f2(i) ...: 40.2 µs ± 729 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each) edit: u/hai_wim pointed out that the speeds are fully equal (difference is within stdev tolerance), as the byte code is exactly the same. So the question really comes down to readability and standardization.
0.53
t3_tfbvh6
1,647,415,266
Python
Approach H2kinfosys to Learn Python Course Effectively
This [**python certification online**](https://www.h2kinfosys.com/courses/python-online-training) course is created for complete beginners, so you don't need any prior programming experience to complete it. The outline is designed to cover the basics of the programming language as well as some advanced topics.
0.67
t3_tfbsr5
1,647,414,945
Python
macOS 12.3 finally deletes its own Python 2, which even die-hard Python fans applaud
0.96
t3_tfbgoe
1,647,413,504
Python
Tool to get path to JSON in python format
I found a tool that you can paste JSON into, provide the key to look for, and the value expected for the key (partial values works too). The result is the path to the value. Wanted to share as I found this useful. https://xenosoftwaresolutions.com/json sample JSON: { "test": [ { "item": true, "checked": false, "info": { "hello": "world" }, "products": [] } ] } result when looking for hello as key and world as value: ["test"][0]["info"]["hello"]
0.78
t3_tf6b85
1,647,395,272
Python
Wednesday Daily Thread: Beginner questions
New to Python and have questions? Use this thread to ask anything about Python, there are no bad questions! This thread may be fairly low volume in replies, if you don't receive a response we recommend looking at r/LearnPython or joining the Python Discord server at [https://discord.gg/python](https://discord.gg/python) where you stand a better chance of receiving a response.
0.67
t3_tf45nb
1,647,388,810
Python
Approximate Pi with 7 lines of code (arctangent series)
[https://www.youtube.com/watch?v=h63eSCNtJLg](https://www.youtube.com/watch?v=h63eSCNtJLg)
0.58
t3_tf2yrl
1,647,385,408
Python
Article: Build a webhook in Python to interact with GitLab.
0.79
t3_tf1c39
1,647,380,997
Python
Which is more Pythonic?
if event_region in match regions: return True else: return False` Or... `Return True if event_region in match_regions else False` Or... `return event_region in match_regions` Where "event_region" is a string and "match_regions" is a list of strings
0.87
t3_tezqe5
1,647,376,725
Python
Django Email Signals - Django App that Actually Solves a Business Problem
In my workplace we make a lot of Django apps and for a number of these Django apps, we configure a lots of emails to be sent. Whenever something changes in the database that meets some condition we send an email. The emails have their own context and each email can be a time consuming to setup. There has to be a better way I thought. And so, I built [django-email-signals](https://github.com/Salaah01/django-email-signals). I build this app to be as plug-and-play as possible with minimal configuration. This Django app allows you to setup email signals right from the admin page Here is a breakdown of what the app currently lets you do: * Configure emails to be sent when some data in some model is changed. * Set some constraints to determine if indeed an email can be sent. * Either write up your email content when setting up a new email signal, or provide a path to a template. * Be able to reference objects and attributes such `instance.user.first_name` right from where you would set your constraints or the email HTML itself.
1
t3_teyws8
1,647,374,670
Python
Introducing Typesplainer: a python type-hint explainer
## What Typesplainer is a Python type hint explainer that explains python type hints in plain English. It is very fast, accurate, and easy to use and understand. Available as a CLI, on the web, and as a Visual Studio Code extension ## Where Website: https://typesplainer.herokuapp.com/\ CLI: https://pypi.org/project/typesplainer/\ Visual Studio Code extension (Alpha): https://marketplace.visualstudio.com/items?itemName=WasiMaster.typesplainer ## Why Wondering WTF is an `Callable[[List[int]], Dict[int, List[Union[str, None]]]]`? typesplainer has got you covered. It's a callable that accepts a list of integers and returns a dictionary that maps integers onto a list of optional strings. Understanding type hints can be hard and time-consuming, especially if they are very big like the example above. This tool helps you understand things like that more easily and faster. ## How Just use the cli if you want to use it anytime and anywhere. Use the website to test the tool before installing or if you want a graphical interface. And since the vscode extension is still in development, I won't recommend that at the moment.
0.84
t3_tevyc4
1,647,368,487
Python
Demystifying Apache Arrow: what is it and when should you use it?
0.91
t3_tettmu
1,647,363,875
Python
Python Web Frameworks
0.67
t3_tehw7k
1,647,322,911
Python
The Boilerplate for Logging in Python
## Use this logging template in your next big project Finding bugs is a common problem in any programming project. To make it easier to find bugs, you probably want to write some print statements to help you debug. Is it helpful? yes. Is it the right way to track events in your code, especially in a big project? no. Python has a built-in logging module that you can use to log messages. Logging not only helps you debug the issues in your code. It also helps you understand the flow of your code especially when you ship to production. It is a very useful tool to identify how your code is behaving whether it is working as expected or not. If not, it can show you different hierarchies of how severe the issue is whether it is an error, a warning, or a debug mode. Without having logging, it's difficult to keep your code maintainable for a long time. Especially when this code is mature. In this tutorial, I'll show you a boilerplate for logging that you can use in your next project. Instead of looking at the documentation every time. ## Division Example Let's take this division example especially when we divide by zero: ```python def divide(dividend, divisor): try: return dividend / divisor except ZeroDivisionError: return "Zero Division error." print(divide(6, 0)) ``` In this case, when we divided 6 by 0 we returned a message string. This message shows that a zero division error during the `ZeroDivisionError` exception occurred. What's the problem with that? The issue here is that we don't know when that happened and how severe the issue is. Is it a warning? an error? or just a piece of information you're printing to the console? The built-in Python's `logging` module helps you better log your code with its features. Let's see how we can use it in this context: ```python import logging # Define a logger instance logger = logging.getLogger(__name__) # Define a stream handler for the console output handler = logging.StreamHandler() # Customize the formatter on the console formatter = logging.Formatter( "%(asctime)s - %(name)s: %(levelname)s - %(message)s", datefmt="%Y-%m-%d %H:%M:%S" ) # Add the formatter to the handler handler.setFormatter(formatter) # Add the stream handler to the logger that we will use logger.addHandler(handler) # Set the level of logging to be INFO instead of the default WARNING logger.setLevel(logging.INFO) def divide(dividend, divisor): try: logger.info(f"Dividing {dividend} by {divisor}") return dividend / divisor except ZeroDivisionError: logger.info("Zero Division error.") print(divide(6, 0)) ``` which would return helpful information like this: ``` 2022-02-23 13:24:41 - __main__: INFO - Dividing 6 by 0 2022-02-23 13:24:41 - __main__: INFO - Zero Division error. ``` ## Wrap Up In this boilerplate, you've seen how to log messages to the console. You've formatted the logs to start with a date and time followed by the name of the module, level of logging, and the log message itself. Check out the [logger module here](https://gist.github.com/EzzEddin/0e8c517a47e678da6a60cc21fdbc5788) and let me know if you have any feedback, thanks!
1
t3_terbh0
1,647,357,423
Python
Python vs SQL for Data Analysis: comparing performance, functionality and dev XP
The clean division of data analysis labor between Python and SQL seems to be fading with tools like dbt, Snowpark and dask-sql. The article shared below compares the two languages in terms of performance, functionality and developer XP. Quick summary: **Performance** Running SQL code on data warehouses is generally faster than Python for querying data and doing basic aggregations. This is because SQL queries move code to data instead of data to code. That said, parallel computing solutions like Dask and others that scale Python code to larger-than-memory datasets can significantly lower processing times compared to traditional libraries like pandas. **Functionality** SQL’s greatest strength is also its weakness: simplicity. For example, writing SQL code to perform iterative exploratory data analysis, data science or machine learning tasks can quickly get lengthy and hard to read. Python lets you write free-form experimental data analysis code and complex mathematical and/or ML code. The absence of a vibrant and reliable third-party library community for SQL is also a problem compared to Python. **Developer XP** Python makes debugging and unit-testing a lot easier and more reliable. While dbt has added code versioning by forcing the use of Git, SQL diffs are still harder to read and manipulate than diffs in Python IMO. **Conclusion** While it's tempting to frame the debate between SQL and Python as a stand-off, the two languages in fact excel at different parts of the data-processing pipeline. One potential rule of thumb to take from this is to **use SQL for simple queries that need to run fast** on a data warehouse, **dbt for organizing more complex SQL models**, and **Python with distributed computing libraries like Dask for free-form exploratory analysis and machine learning code** and/or code that needs to be reliably unit tested.  Full article: [https://airbyte.com/blog/sql-vs-python-data-analysis](https://airbyte.com/blog/sql-vs-python-data-analysis)
0.69
t3_tequ97
1,647,356,144
Python
Use Python to Transcribe an Audio File in an S3 Bucket in 3 Steps
Hey guys! I wrote a [mini-article](https://www.assemblyai.com/blog/transcribing-audio-files-in-an-s3-bucket-with-assemblyai/) on **how to transcribe an audio file in an S3 bucket in 3 simple steps**. Figured it might be helpful for people learning to use Python, JSON, AWS, etc.!
0.95
t3_teqkc2
1,647,355,373
Python
Processing large JSON files in Python without running out memory
nan
0.95
t3_tepn58
1,647,352,799
Python
Python Class Constructors: Control Your Object Instantiation – Real Python
nan
0.67
t3_teozl2
1,647,350,835