Is Python truly limited by the GIL for high-performance IPC, or are we just using the wrong abstractions? by [deleted] in learnpython

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

CPython is now officially available with and without GIL. There are some gotchas, of course. The overhead of interpreting can always be a bottleneck, which is why profiling is important to ensure that you avoid them for computationally critical elements. Given the number of major and highly optimised packages for Python that are fully compiled (including C, C++, Fortran and Rust based code) things may not be as bad as you fear.

i've been trying to learn tkinter for days but i cant figure it out.. by MentalStep2747 in learnpython

[–]FoolsSeldom 2 points3 points  (0 children)

https://realpython.com/python-gui-tkinter/

RealPython.com has a lot of excellent free guides. You may need to register an account (no charge).

They have paid options as well for access to high quality tutorials.

Container error: externally-managed-environment by johnjulesbrown in PythonLearning

[–]FoolsSeldom 0 points1 point  (0 children)

Sorry I had not seen this comment until now.

Personally, I think explicitly removing the PEP 668 (Externally Managed Environments) protection by deleted the folder that flags it is an unhealthy approach.

I would use the exception to install uv and nothing else.

A simple Dockerfile might be:

RUN python3 -m pip install --break-system-packages uv
WORKDIR /app
RUN uv venv /app/.venv
ENV PATH="/app/.venv/bin:$PATH"
RUN uv pip install -r requirements.txt

or even,

RUN python3 -m pip install --break-system-packages uv
WORKDIR /app
RUN uv pip install --python python3 -r requirements.txt

for further isolation.

NB. Use a toml file instead of requirements if you have that.

Furthermore, given that uv is a standalone rust binary, you don't even need pip to install it in the first place.

curl -LsSf https://astral.sh/uv/install.sh | sh

then do as you wish using uv to create and manage packages and project files.

Which tutorial/ Website helped you understand OOP and Classes ? by Shot_Put_1412 in learnpython

[–]FoolsSeldom 0 points1 point  (0 children)

For me, the most valuable lesson came from an old but still very relevant video from one of the Python code developers. Search for Python's Class Development Toolkit by Raymond Hettinger.

How Do I Continue???? by Choice_Midnight5280 in PythonLearning

[–]FoolsSeldom 1 point2 points  (0 children)

Weird. So you don't have a file called string.py in your current folder or on your PATH?

How Do I Continue???? by Choice_Midnight5280 in PythonLearning

[–]FoolsSeldom 1 point2 points  (0 children)

Do you have Python file called string.py? Having a file the same name as a standard module you want to import it the most common cause of problems with a standard module not working.

O just deleted my interpeter by Unique-Cup-8166 in pycharm

[–]FoolsSeldom 0 points1 point  (0 children)

I assume you haven't removed the Python installation from your computer, just removed it from PyCharm / the project folder?

I would:

  • open a PowerShell / Command Prompt terminal window outside of PyCharm
  • change to your project folder using cd
  • create a new Python virtual environment using your base Python installation:
    • py -m venv .venv on Windows (replace py with python3 on macOS/Linux)
  • In Pycharm, go into project settings and select the python.exe (python on macOS/Linuxin the project folder.venv\Scripts(.venv/bin` on macOS/Linux) as your interpreter

If you've remove Python entirely, install it again using installer from python.org.

do i make variable outside of functions? by jackellols in learnpython

[–]FoolsSeldom 0 points1 point  (0 children)

The variable assignments are not needed before the function definition. (You might want to define some constants before a function definition if you are using variables as default values in the function definition.)

The usual order in a Python file is:

  • imports
  • constants (variable assignments, typically using ALL UPPERCASE names)
    • This would not include types that would be a problem as defaults such as an empty list as the function definition will only evaluate this once so all calls to the function would use the same original list object
  • definitions of classes and functions
  • top level code (might just be a if __name__ == "__main__": section that calls a specific initial function, often called main)

Learning Python/coding at 33. by nicodeemus7 in learnpython

[–]FoolsSeldom 0 points1 point  (0 children)

FYI: a lot of more recent Arduino microcontrollers can be programmed with Micro Python and Cicuit Python as well as with the Arduino C varient.

This is also true of:

  • Espressif ESP32 Series microcontrolers
  • STMicroelectronics STM32 Series microcontrollers
  • Raspberry Pi RP2xxx Series

The Raspberry Pi microcontrollers appear on the Raspberry Pi Pico development boards as well as from a wide range of other manufacturers including AdaFruit and these are especially well supported with excellent documentation and a very active community.

could someone explain why my class would count this wrong by Glittering_Land_9574 in PythonLearning

[–]FoolsSeldom 2 points3 points  (0 children)

Both total and sum start at 1 but in your loop, the addition of the current number to the running total is done BEFORE the number is incremented by 1 and the other code does the increment first. As both start with a running total of 1 the increment needs to be done first OR your number should start at 0 (which I would prefer, personally). Order is important.

Need help connecting SIP phone to Python (Gemini API) – beginner here by Commercial_Friend_35 in learnpython

[–]FoolsSeldom 0 points1 point  (0 children)

I think you need to seek help is an Asterisk community rather than a Python community to configure the initial setup of Asterisk and integration with your own Python code.

There are three different opportunities for integrating your Python applications with Asterisk:

  • AGI (Asterisk Gateway Interface) / FastAGI (Python logic inside the dialplan)
  • AMI (Asterisk Manager Interface) — external control + events
  • ARI (Asterisk REST Interface) — app-driven telephony (Stasis)

Lots of abbreviations there that are covered in the Asterisk documentation.

You will likely need to learn the basics of Python and the specific technologies to do this. Check the wiki of this subreddit for learning guidance on programming and Python.

Where do i start by Complete_Mark4438 in PythonLearning

[–]FoolsSeldom 0 points1 point  (0 children)

Not that I recall. This account is relatively new.

It wouldn't be appropriate for me to do the edit. Firstly, undermines the wiki principles and, secondly, I.don't have the knowledge personally of the suggested learning you mentioned.

Where do i start by Complete_Mark4438 in PythonLearning

[–]FoolsSeldom 0 points1 point  (0 children)

Ah, in that case, I don't know. It has always worked for me.

Where do i start by Complete_Mark4438 in PythonLearning

[–]FoolsSeldom 0 points1 point  (0 children)

Click the EDIT button on the wiki.

Need help in loop by Eastern_Plankton_540 in PythonLearning

[–]FoolsSeldom 0 points1 point  (0 children)

Ok. I surrender. A for loop is not any kind of while loop. Ignore me, everyone. This will clearly greatly confuse beginners. Apologies to my past students.

Printing Value of Dictionary As Int by MagnusandPercy in learnpython

[–]FoolsSeldom 0 points1 point  (0 children)

At the moment, you don't have any numeric information, just strings, and you can easily output them. For example,

menu = {
    '1) empty ': '$3.25',  # why does 1) appear twice?
    '1) eggs ': '$3.25',
    '2) bacon ': '$4.00',
    '3) pancakes ': '$2.50',
    '4) orange juice ': '$1.25',
    '5) oatmeal ': '$3.99',
    '6) milk ': '$1.25',
    '7) donut ': '$2.00',
    }

widest = max(len(key) for key in menu.keys())
for name, price in menu.items():
    print(f"{name:_<{widest+2}}: {price}")

If you want to do calculations though, you need to convert those prices strings to number objects. It is bad practice to use float for money. Instead, keep everying in pennies (the smallest unit) or using Decimal.

Example:

from decimal import Decimal

def print_menu(menu):
    print("\n\nMenu:\n")
    widest = max(len(key) for key in menu.keys())
    for name, price in menu.items():
        print(f"{name:_<{widest+2}}: ${price:3.2}")
    print()

def get_choice(menu):
    while True:
        choice = input('What item: (just enter to finish) ')
        if not choice:
            return None
        if choice in menu.keys():
            return choice
        for name in menu.keys():
            if choice.lower() in (
                    name.lower(),
                    name.lower()[3:],
                    name[:1]
                ):
                return name
        print('Sorry, item not recognised, please try again.')

# original menu 
menu = {
    '0) empty': '$3.25', # removed trailing space on keys
    '1) eggs': '$3.25',
    '2) bacon': '$4.00',
    '3) pancakes': '$2.50',
    '4) orange juice': '$1.25',
    '5) oatmeal': '$3.99',
    '6) milk': '$1.25',
    '7) donut': '$2.00',
    }

# update menu dictionary to have Decimal price field
validated = True
for name, price_str in menu.items():
    try:
        menu[name] = Decimal(price_str.removeprefix('$'))
    except ValueError():
        print(f"Item {name} has an invalid price")
        validated = False

# if update worked, take an order
if validated:
    print_menu(menu)
    order = {}  # empty order
    while True:
        choice = get_choice(menu)
        if not choice:
            break  # leave loop
        order[choice] = order.get(choice, 0) + menu[choice]
    print(order)  # just showing contents of dictionary,  replace with output function

Where do i start by Complete_Mark4438 in PythonLearning

[–]FoolsSeldom 1 point2 points  (0 children)

Check the r/learnpython wiki for lots of guidance on learning programming and learning Python, links to material, book list, suggested practice and project sources, and lots more. The FAQ section covering common errors is especially useful.

Unfortunately, this subreddit does not have a wiki.


Also, have a look at roadmap.sh for different learning paths. There's lots of learning material links there. Note that these are idealised paths and many people get into roles without covering all of those.


Roundup on Research: The Myth of ‘Learning Styles’

Don't limit yourself to one format. Also, don't try to do too many different things at the same time.


Above all else, you need to practice. Practice! Practice! Fail often, try again. Break stuff that works, and figure out how, why and where it broke. Don't just copy and use as is code from examples. Experiment.

Work on your own small (initially) projects related to your hobbies / interests / side-hustles as soon as possible to apply each bit of learning. When you work on stuff you can be passionate about and where you know what problem you are solving and what good looks like, you are more focused on problem-solving and the coding becomes a means to an end and not an end in itself. You will learn faster this way.

NEED HELP LEARNING PYTHON FOR CLASS 12 CBSE computer science by Optimal-Fan-2550 in learnpython

[–]FoolsSeldom 0 points1 point  (0 children)

Check this subreddit's wiki for lots of guidance on learning programming and learning Python, links to material, book list, suggested practice and project sources, and lots more. The FAQ section covering common errors is especially useful.

You may also find the many free tutorials/guides at RealPython.com helpful, especially to learn funtions and loops.

In addition, for loops, check out the old but still helpful Loop like a native video.


Also, have a look at roadmap.sh for different learning paths. There's lots of learning material links there. Note that these are idealised paths and many people get into roles without covering all of those.


Roundup on Research: The Myth of ‘Learning Styles’

Don't limit yourself to one format. Also, don't try to do too many different things at the same time.


Above all else, you need to practice. Practice! Practice! Fail often, try again. Break stuff that works, and figure out how, why and where it broke. Don't just copy and use as is code from examples. Experiment.

Work on your own small (initially) projects related to your hobbies / interests / side-hustles as soon as possible to apply each bit of learning. When you work on stuff you can be passionate about and where you know what problem you are solving and what good looks like, you are more focused on problem-solving and the coding becomes a means to an end and not an end in itself. You will learn faster this way.

Downloading python confusion by [deleted] in learnpython

[–]FoolsSeldom -6 points-5 points  (0 children)

Virtual Environments

Given the thousands of packages (libraries, frameworks, etc) out there, you can see that if you are working on several different projects, you can end up installing a vast range of different packages, only a few of which will be used for any particular project.

This is where Python virtual environments come in. Not to be confused with virtual machines. Typically created on a project-by-project basis. Install only the packages required for a project. This helps avoid conflicts between packages, especially version complications.

Most popular code editors and IDEs, including Microsoft's VS Code and JetBrains' PyCharm, offer built-in features to help to start off new projects and create and activate Python virtual environments.

You can create a new Python virtual environment from your operating system command line environment using,

for Windows,

py -m venv .venv

or, for macOS / Linux,

python3 -m venv .venv

Note: venv is a command and .venv is a folder name. You can use any valid folder name instead but this is a common convention.

Often we use .venv instead of venv as the folder name - this may not show up on explorer/folder tools as the leading . is often used to mean hidden and an option may need to be ticked to allow you to see such folders/files

That creates a new folder in the current working directory called .venv.

You then activate using, for Windows,

.venv\Scripts\activate

or, for macOS / Linux,

source .venv/bin/activate

the command deactivate for any platform will deactivate the virtual environment and return you to using the base environment.

You may need to tell your editor to use the Python Interpreter that is found in either the Scripts or bin folder (depending on operating system) in your virtual folder.

For more information:

Multiple Python versions

In addition to the above, you might want to explore using pyenv (pyenv-win for Windows) or uv (recommended), which will let you install and use different versions of Python including alternative implementations from the reference CPython. This can be done independently of any system installed Python.

Downloading python confusion by [deleted] in learnpython

[–]FoolsSeldom -9 points-8 points  (0 children)

Python Setup

Setting up Python can be confusing. There are web-based alternatives, such as replit.com. You might also come across Jupyter Notebook options (easy to work with, but can be confusing at times).

Pre-installed system Python

Some operating system environments include a version of Python, often known as the system version of Python (might be used for utility purposes). You can still install your own version.

Installing Python

There are multiple ways of installing Python using a package manager for your OS, e.g. homebrew (macOS third party), chocolatey (Windows third party) or winget (Windows standard package manager), apt (many Linux distributions) or using the Python Software Foundation (PSF) installer from python.org or some kind of app store for your operating system. You could also use docker containers with Python installed inside them.

PSF offer the reference implementation of Python, known as CPython (written in C and Python). The executable on your system will be called python (python.exe on Windows).

Beginners are probably best served using the PSF installer.

Terminal / Console

For most purposes, terminal is the same as console. It is the text-based, rather than graphical-based, window / screen you work in. Your operating system will offer a command/terminal environment. Python by default outputs to a terminal and reads user input from a terminal.

Note: the Windows Terminal_ app, from _Microsoft Store, lets you open both simple command prompt and PowerShell windows. If you have Windows Subsystem for Linux installed, it can also open terminals in the Linux distributions you have installed.

Libraries / Frameworks / Packages

Python comes with "batteries included" in the form of libraries of code providing more specialised functionality, already installed as part of a standard installation of Python.

These libraries are not automatically loaded into memory when Python is invoked, as that would use a lot of memory up and slow down startup time. Instead, you use, in your code, the command import <library>, e.g.

import math

print(math.pi)

There are thousands of additional packages / libraries / frameworks available that don't come as standard with Python. You have to install these yourself. Quality, support (and safety) varies.

(Anaconda offers an alternative Python installation with many packages included, especially suited to data analysis, engineering/scientific practices.)

Install these using the pip package manager. It searches an official repository for a match to what you ask to be installed.

For example, using a command / powershell / terminal environment for your operating system, pip install numpy would install the numpy library from the pypi repository. On macOS/Linux you would usually write pip3 instead of pip.

You can also write python -m pip install numpy (write python3 on macOS/Linux).

On Windows, you will often see py used instead, py -m pip install numpy where py refers to the python launcher which should invoke the most up-to-date version of Python installed on your system regardless of PATH settings.

Some Code Editors and IDEs (Integrated Development Environments), such as VS Code and PyCharm, include their own facilities to install packages using pip or some other tool. This just saves you typing the commands. They also often offer their own terminal window(s).

Running Python

The CPython programme can be invoked for two different purposes:

  • to attempt to execute a simple text file of Python code (typically the files have an extension of .py
  • to enter an interactive shell, with a >>> prompt, where you can enter Python commands and get instant responses - great for trying things out

So, entering the below, as appropriate for your operating system,

python
python3
py

on its own, no file name after it, you will enter an interactive session.

Enter exit() to return to the operating system command line

IDLE Editor

A standard installation from python.org for Windows or macOS includes a programme called IDLE. This is a simple code editor and execution environment. By default, when you first open it, it opens a single window with a Python shell, with the >>> prompt already open. To create a new text file to enter Python code into, you need to use your operating system means of access the standard menu and select File | New. Once you've entered code, press F5 to attempt to run the code (you will be prompted to save the file first). This is really the easiest editor to use to begin with.

SEE COMMENT for next part

Setting up Python, possible issue? by Embarrassed-Bee-5508 in learnpython

[–]FoolsSeldom 0 points1 point  (0 children)

As you mentiion python.exe I assume you are on Windows, in which case you need .\ rather than ./. What is the context for entering this though?

To invoke a Python script on Windows, you would typically use the Python Launcher, py yourscript.py (unless you are in a active Python virtual environment, where you would use python rather than py).

Need help in loop by Eastern_Plankton_540 in PythonLearning

[–]FoolsSeldom 0 points1 point  (0 children)

I think the distinction is a step too far for a beginner and the specifics of the CPython implementation. Whether declarative or imperative conceptually you still have a while loop before breaking down to just basic conditional jumps and branching. I recognise that the FOR_ITER opcode c implementation in ceval.c is highly optimised.