1
30
Python Insider: Python 3.12.4 released (pythoninsider.blogspot.com)
submitted 3 weeks ago by [email protected] to c/[email protected]
2
36
Welcome to c/Python! (programming.dev)
submitted 1 year ago by [email protected] to c/[email protected]

Welcome to c/Python, the go to place to discuss Python tools, techniques, and news.

We're just getting started, so please use this thread to suggest what this community should look like, what it should cover, and how it should operate.

3
9
submitted 3 days ago by [email protected] to c/[email protected]

I have a repository that contains multiple programs:

.
└── Programs
    ├── program1
    │   └── Generic_named.py
    └── program2
        └── Generic_named.py

I would like to add testing to this repository.

I have attempted to do it like this:

.
├── Programs
│   ├── program1
│   │   └── Generic_named.py
│   └── program2
│       └── Generic_named.py
└── Tests
    ├── mock
    │   ├── 1
    │   │   └── custom_module.py
    │   └── 2
    │       └── custom_module.py
    ├── temp
    ├── test1.py
    └── test2.py

Where temp is a folder to store each program temporarily with mock versions of any required imports that can not be stored directly with the program.

Suppose we use a hello world example like this:

cat Programs/program1/Generic_named.py
import custom_module

def main():
    return custom_module.out()


cat Programs/program2/Generic_named.py
import custom_module

def main():
    return custom_module.out("Goodbye, World!")


cat Tests/mock/1/custom_module.py
def out():return "Hello, World!"


cat Tests/mock/2/custom_module.py
def out(x):return x

And I were to use these scripts to test it:

cat Tests/test1.py
import unittest
import os
import sys
import shutil

if os.path.exists('Tests/temp/1'):
    shutil.rmtree('Tests/temp/1')

shutil.copytree('Tests/mock/1', 'Tests/temp/1/')
shutil.copyfile('Programs/program1/Generic_named.py', 'Tests/temp/1/Generic_named.py')

sys.path.append('Tests/temp/1')
import Generic_named
sys.path.remove('Tests/temp/1')

class Test(unittest.TestCase):
    def test_case1(self):
            self.assertEqual(Generic_named.main(), "Hello, World!")

if __name__ == '__main__':
    unittest.main()



cat Tests/test2.py
import unittest
import os
import sys
import shutil

if os.path.exists('Tests/temp/2'):
    shutil.rmtree('Tests/temp/2')

shutil.copytree('Tests/mock/2', 'Tests/temp/2')
shutil.copyfile('Programs/program2/Generic_named.py', 'Tests/temp/2/Generic_named.py')

sys.path.append('Tests/temp/2')
import Generic_named
sys.path.remove('Tests/temp/2')

class Test(unittest.TestCase):
    def test_case1(self):
            self.assertEqual(Generic_named.main(), "Goodbye, World!")

if __name__ == '__main__':
    unittest.main()

Both tests pass when run individually:

python3 -m unittest Tests/test1.py
.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK


python3 -m unittest Tests/test2.py
.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK

However, they fail when being run together:

python3 -m unittest discover -p test*.py -s Tests/
.F
======================================================================
FAIL: test_case1 (test2.Test)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/s/Documents/Coding practice/2024/Test Mess/1/Tests/test2.py", line 18, in test_case1
    self.assertEqual(Generic_named.main(), "Goodbye, World!")
AssertionError: 'Hello, World!' != 'Goodbye, World!'
- Hello, World!
+ Goodbye, World!


----------------------------------------------------------------------
Ran 2 tests in 0.001s

FAILED (failures=1)

If I try to use a different temporary name for one of the scripts I am trying to test,

cat Tests/test2.py
import unittest
import os
import sys
import shutil

if os.path.exists('Tests/temp/2'):
    shutil.rmtree('Tests/temp/2')

shutil.copytree('Tests/mock/2', 'Tests/temp/2')
shutil.copyfile('Programs/program2/Generic_named.py', 'Tests/temp/2/Generic_named1.py')

sys.path.append('Tests/temp/2')
import Generic_named1
sys.path.remove('Tests/temp/2')

class Test(unittest.TestCase):
    def test_case1(self):
            self.assertEqual(Generic_named1.main(), "Goodbye, World!")

if __name__ == '__main__':
    unittest.main()

Then I get a different error:

python3 -m unittest discover -p test*.py -s Tests/
.E
======================================================================
ERROR: test_case1 (test2.Test)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/s/Documents/Coding practice/2024/Test Mess/2/Tests/test2.py", line 18, in test_case1
    self.assertEqual(Generic_named1.main(), "Goodbye, World!")
  File "/home/s/Documents/Coding practice/2024/Test Mess/2/Tests/temp/2/Generic_named1.py", line 4, in main
    return custom_module.out("Goodbye, World!")
TypeError: out() takes 0 positional arguments but 1 was given

----------------------------------------------------------------------
Ran 2 tests in 0.001s

FAILED (errors=1)

It seems to be trying to import the same file, despite me using a different file from a different path with the same name. This seems strange, as I've been making sure to undo any changes to the Python Path after importing what I wish to test. Is there any way to mock the path? I can't change the name of the custom_module, as that would require changing the programs I wish to test.

How should I write, approach, or setup these tests such that they can be tested with unittest discover the same as they can individually?

4
44
submitted 6 days ago by [email protected] to c/[email protected]
5
2
submitted 3 days ago by [email protected] to c/[email protected]

This is slyautomation and I am thrilled to welcome you to this in-depth tutorial where we will unravel the intricacies of training an aimbot using the cutting-edge YOLOv8.

6
24
submitted 1 week ago by [email protected] to c/[email protected]
7
13
submitted 1 week ago by [email protected] to c/[email protected]
8
7
submitted 1 week ago by [email protected] to c/[email protected]

This happens if I use set_time or set_position. Is this typical, or am I just not doing it right?

This is on a Pi Zero 2 W, so not the most powerful, but should be able to handle this.

These are the relevant bits of how I'm setting up the player:

    self._vlc = vlc.Instance()
    self._player = self._vlc.media_player_new()
    self._list_player = self._vlc.media_list_player_new()
    self._list_player.set_media_player(self._player)

    playlist = self._vlc.media_list_new()
    for index in self._play_order:
      playlist.add_media(self._vlc.media_new_path(self._songs[index]))

    self._list_player.stop()
    self._list_player.set_media_list(playlist)
    self._list_player.play()

And trying to seek is just this:

    self._player.set_time(_s_to_ms(seconds))

Any ideas would be greatly appreciated!

9
25
submitted 1 week ago by [email protected] to c/[email protected]

Hi, I want to know what is the best way to keep the databases I use in different projects? I use a lot of CSVs that I need to prepare every time I'm working with them (I just copy paste the code from other projects) but would like to make some module that I can import and it have all the processes of the databases for example for this database I usually do columns = [(configuration of, my columns)], names = [names], dates = [list of columns dates], dtypes ={column: type},

then database_1 = pd.read_fwf(**kwargs), database_2 = pd.read_fwf(**kwargs), database_3 = pd.read_fwf(**kwargs)...

Then database = pd.concat([database_1...])

But I would like to have a module that I could import and have all my databases and configuration of ETL in it so I could just do something like 'database = my_module.dabase' to import the database, without all that process everytime.

Thanks for any help.

10
18
submitted 1 week ago* (last edited 1 week ago) by [email protected] to c/[email protected]

I'm new to programming a bit, and am learning python so I can learn flask, using the python crash course book. I was learning about list comprehension but it briefly talks about it. If I do

list[list.append(value) for value in range(1, 20)]

it doesn't work. Would this be some sort of recursive expression that is not possible?

11
18
submitted 1 week ago by [email protected] to c/[email protected]

Hi,

I have to interface with systems that use iso-8859-x encoding (not by choice...), and I'm surprised that the following doesn't throw an error:

>>> str(bytes(range(256)), encoding="iso-8859-1", errors="strict")
'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7f\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa0¡¢£¤¥¦§¨©ª«¬\xad®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ'

Bytes in the 0x80—0x9f range are not valid iso-8859-1, and I was expecting the above to raise a DecodeError of some sort; instead it looks like those are passed through.

I'm perfectly happy with this behaviour, I would like to make sure I can depend on it. Can I take an arbitrary byte buffer, decode as ISO-8859-1, and never get any error? Is it guaranteed to be lossless ?

12
33
submitted 1 week ago by [email protected] to c/[email protected]

So, I have a python script I'd like to run from time to time from the CLI (on Linux) that resides inside a venv. What's the recommended/intended way to do this?
Write a wrapper shell script and put it inside a $PATH-accessible directory that activates the virtual environment, runs the python script and deactivates the venv again? This seems a bit convoluted, but I can't think of a better way.

13
15
submitted 2 weeks ago by [email protected] to c/[email protected]
14
125
submitted 3 weeks ago by [email protected] to c/[email protected]
15
35
submitted 3 weeks ago* (last edited 3 weeks ago) by [email protected] to c/[email protected]
16
75
submitted 3 weeks ago by [email protected] to c/[email protected]
17
30
submitted 3 weeks ago by [email protected] to c/[email protected]

I started working through the 100 Days of Code course of Udemy last February, and I'm in the home stretch. I'm on the final lessons, which are really just prompts for projects. No hand holding, just a brief description of the goal. I recently finished a tkinter GUI program, the goal of which was to enable adding text watermarks.

I took a few liberties--mainly, I made it possible to layer a png on top of the background. It was a really fun project and quickly grew more complicated than I expected it to. I got some hands on experience with the Single Responsibility Principle, as I started off doing everything in my Layout class.

Eventually, I moved all the stuff that actually involved manipulating the Image objects to an ImageManager class. I feel like I could have gotten even more granular. That's one thing I would love to get some feedback on. How would a more experienced programmer have architected this program?

Anyway, I guess this preamble is long enough. I'm going to leave a link to the repository here. I would have so much appreciation for anyone who took the time to look at the code, or even clone the repo and see if my instructions for getting it to run on your machine work.

Watermark GUI Repo

18
42
submitted 3 weeks ago by [email protected] to c/[email protected]

I'm currently learning Python and am learning about very basic functions such as int(), float(), and input().

I have the first two down pat, but I'm struggling to understand the last. The example I'm looking at is found at 12:26 of this video:

nam = input('Who are you? ')
print('Welcome', nam)

Who are you? Chuck
Welcome Chuck

In this case, wouldn't nam be a variable equal to the text on the right side of the = sign?

In which case, if nam is equal to input('Who are you? '), then wouldn't print('Welcome', nam) just result in

Welcome input(Who are you? )?

Obviously not (nor does it work in a compiler), which leads me to believe I'm clearly misunderstanding something. But I've rewatched that section of the video several times, and looked it up elsewhere on the web, and I just can't wrap my head around it.

Could someone help me with this?

Thanks.

19
24
submitted 3 weeks ago by [email protected] to c/[email protected]

If I run this

#!/bin/bash

ARCH=$(python fetch_architecture.py)
if [ $ARCH == "aarch64" -o $ARCH == "armv71" ] ; then
    export PATH=/opt/local/llvm/bin:${PATH}
    cd /app
    RUSTFLAGS="-C linker=lld" wasm-pack build --target web --release plume-front
else
    wasm-pack build --target web --release plume-front
fi

via the terminal, it works just fine. But when I run it via the Dockerfile,

COPY . . 
RUN cargo install wasm-pack 
RUN chmod a+x ./script/plume-front.sh 
RUN sleep 1 
RUN ./script/plume-front.sh

It says python: command not found and then [: too many arguments

20
21
What Git library to choose? (discuss.tchncs.de)
submitted 1 month ago by [email protected] to c/[email protected]

I happen to write a lot of python code dealing with git repositories. Currently I am calling the git command line tool from python and interpret the output.

This solution really doesn't scale well. Can you recommend a python library that wraps git functionality?

I have found three:

  • GitPython: Seems to work well, but it is in maintenance mode, unlikely to be improved. It also does not have any type hints making working with it annoying.
  • pygit2: Seems well supported and has type hints. But it also seems very low level and pretty tedious to use.
  • dulwich: Looks very promising feature wise but I'm unsure how well it is supported. It seems like an ambitious project being largely done by just one person.
21
26
submitted 1 month ago by [email protected] to c/[email protected]
22
43
submitted 1 month ago by [email protected] to c/[email protected]

Neato

23
28
submitted 1 month ago by [email protected] to c/[email protected]
24
28
Python beginner (feddit.uk)
submitted 1 month ago by [email protected] to c/[email protected]

Good evening, everyone. I have, but one quick inquiry. What are the best resources in your opinion to learn python by yourself as a complete beginner? Thank you all

25
7
submitted 1 month ago* (last edited 1 month ago) by [email protected] to c/[email protected]

Solved: Thanks to a user with this reply: https://programming.dev/comment/10034690


cross-posted from: https://beehaw.org/post/13901165

Hi all. I have a little problem and don't know how to solve. A CLI program in Python is broken since Python 3.12. It was working in Python 3.11. The reason is, that Python 3.12 changed how subclassing of a pathlib.Path works (basically fixed an issue), which now breaks a workaround.

The class in question is:

class File(PosixPath):
    def __new__(cls, *args: Any, **kwargs: Any) -> Any:
        return cls._from_parts(args).expanduser().resolve()  # type: ignore

    def __init__(self, source: str | Path, *args: Any) -> None:
        super().__init__()
        self.__source = Path(source)

    @property
    def source(self) -> Path:
        return self.__source

    @property
    def modified(self) -> Time:
        return Time.fromtimestamp(os.path.getmtime(self))

    @property
    def changed(self) -> Time:
        return Time.fromtimestamp(os.path.getctime(self))

    @property
    def accessed(self) -> Time:
        return Time.fromtimestamp(os.path.getatime(self))

    # Calculate sha512 hash of self file and compare result to the
    # checksum found in given file. Return True if identical.
    def verify_sha512(self, file: File, buffer_size: int = 4096) -> bool:
        compare_hash: str = file.read_text().split(" ")[0]
        self_hash: str = ""
        self_checksum = hashlib.sha512()
        with open(self.as_posix(), "rb") as f:
            for chunk in iter(lambda: f.read(buffer_size), b""):
                self_checksum.update(chunk)
            self_hash = self_checksum.hexdigest()
        return self_hash == compare_hash

and I get this error when running the script:

Traceback (most recent call last):
File "/home/tuncay/.local/bin/geprotondl", line 1415, in 
sys.exit(main())
^^^^^^
File "/home/tuncay/.local/bin/geprotondl", line 1334, in main
arguments, status = parse_arguments(argv)
^^^^^^^^^^^^^^^^^^^^^
File "/home/tuncay/.local/bin/geprotondl", line 1131, in parse_arguments
default, status = default_install_dir()
^^^^^^^^^^^^^^^^^^^^^
File "/home/tuncay/.local/bin/geprotondl", line 1101, in default_install_dir
steam_root: File = File(path)
^^^^^^^^^^
File "/home/tuncay/.local/bin/geprotondl", line 97, in __new__
return cls._from_parts(args).expanduser().resolve()  # type: ignore
^^^^^^^^^^^^^^^
AttributeError: type object 'File' has no attribute '_from_parts'. Did you mean: '_load_parts'?

Now replacing _from_parts with _load_parts does not work either and I get this message in that case:

Traceback (most recent call last):
File "/home/tuncay/.local/bin/geprotondl", line 1415, in 
sys.exit(main())
^^^^^^
File "/home/tuncay/.local/bin/geprotondl", line 1334, in main
arguments, status = parse_arguments(argv)
^^^^^^^^^^^^^^^^^^^^^
File "/home/tuncay/.local/bin/geprotondl", line 1131, in parse_arguments
default, status = default_install_dir()
^^^^^^^^^^^^^^^^^^^^^
File "/home/tuncay/.local/bin/geprotondl", line 1101, in default_install_dir
steam_root: File = File(path)
^^^^^^^^^^
File "/home/tuncay/.local/bin/geprotondl", line 97, in __new__
return cls._load_parts(args).expanduser().resolve()  # type: ignore
^^^^^^^^^^^^^^^^^^^^^
File "/usr/lib/python3.12/pathlib.py", line 408, in _load_parts
paths = self._raw_paths
^^^^^^^^^^^^^^^
AttributeError: 'tuple' object has no attribute '_raw_paths'

I have searched the web and don't understand how to fix this. Has anyone an idea what to do?

view more: next ›

Python

5934 readers
6 users here now

Welcome to the Python community on the programming.dev Lemmy instance!

📅 Events

October 2023

November 2023

PastJuly 2023

August 2023

September 2023

🐍 Python project:
💓 Python Community:
✨ Python Ecosystem:
🌌 Fediverse
Communities
Projects
Feeds

founded 1 year ago
MODERATORS