Python

7338 readers
27 users here now

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

📅 Events

PastNovember 2023

October 2023

July 2023

August 2023

September 2023

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

founded 2 years ago
MODERATORS
1
2
 
 

It's currently in its third edition, published November 2024.

ISBN-10: 0-13-817218-8

ISBN-13: 978-0-13-817218-3

I've discovered it (in its second edition) in my local library just yesterday. Even what little I've read so far has significantly improved my understanding, e.g. about decorators.

The testimonials for second edition are really something:

“I have been recommending this book enthusiastically since the first edition appeared in 2015. This new edition, updated and expanded for Python 3, is a treasure trove of practical Python programming wisdom that can benefit pro- grammers of all experience levels.”

—Wes McKinney, Creator of Python Pandas project, Director of Ursa Labs

“If you’re coming from another language, this is your definitive guide to taking full advantage of the unique features Python has to offer. I’ve been working with Python for nearly twenty years and I still learned a bunch of useful tricks, especially around newer features introduced by Python 3. Effective Python is crammed with actionable advice, and really helps define what our community means when they talk about Pythonic code.”

—Simon Willison, Co-creator of Django

“Now that Python 3 has finally become the standard version of Python, it’s already gone through eight minor releases and a lot of new features have been added throughout. Brett Slatkin returns with a second edition of Effective Python with a huge new list of Python idioms and straightforward recommendations, catching up with everything that’s introduced in version 3 all the way through 3.8 that we’ll all want to use as we finally leave Python 2 behind. Early sections lay out an enormous list of tips regarding new Python 3 syntaxes and concepts like string and byte objects, f-strings, assignment expressions (and their special nickname you might not know), and catch-all unpacking of tuples. Later sections take on bigger subjects, all of which are packed with things I either didn’t know or which I’m always trying to teach to others, including ‘Metaclasses and Attributes’ (good advice includes ‘Prefer Class Decorators over Metaclasses’ and also introduces a new magic method ‘init_subclass()’ I wasn’t familiar with), ‘Concurrency’ (favorite advice: ‘Use Threads for Blocking I/O, but not Parallelism,’ but it also covers asyncio and coroutines correctly) and ‘Robustness and Performance’ (advice given: ‘Profile before Optimizing’). It’s a joy to go through each section as everything I read is terrific best practice information smartly stated, and I’m considering quoting from this book in the future as it has such great advice all throughout. This is the definite winner for the ‘if you only read one Python book this year...’ contest. —Mike Bayer, Creator of SQLAlchemy

More testimonials are available under the link above.

Book website: https://effectivepython.com/ (Don't buy from Amazon, of course.)

If you're like me and prefer printed books, look up the ISBN at euro-book (which also offers portals for Brasil, Mexico and the USA) to find any affordable used copies.

3
4
 
 
5
6
 
 

I am learning both Greek and Python right now, so I decided to make a simple program that quizzes you on the translations by providing it in Greek and asking for English, and if you provide the English, it will output the Greek if it is in the dictionary.

Feel free to take and modify this for your own uses if interested! It would be as simple as replacing the Greek dictionary and references with anything else. :)

import random, sys

greekTranslation = {
    'Γεια σας': 'Hello',
    'Καλημέρα': 'Good morning',
    'Καλησπέρα': 'Good evening',
    'Ευχαριστώ': 'Thank you',
    'Παρακαλώ': 'Please',}

def practiceGreek():
    greekPhrase = random.choice(list(greekTranslation.keys()))
    print('')
    print(f'What is the translation of "{greekPhrase}"?')
    print('')
    answer = input('Your answer: ')
    if answer.strip().lower() == greekTranslation[greekPhrase].lower():
        print('')
        print('That is correct!')
        print('')
    else:
        print('')
        print(f'Incorrect! The correct translation is "{greekTranslation[greekPhrase]}".')
        print('')

def translateToGreek():
    print('')
    print('What would you like to translate into Greek?')
    print('')
    englishPhrase = input().strip().lower()
    reverseTranslation = {v.lower(): k for k, v in greekTranslation.items()}
    greekPhrase = reverseTranslation.get(englishPhrase)
    
    if greekPhrase:
        print('')
        print(f'The Greek phrase is: "{greekPhrase}"')
        print('')
    else:
        print('')
        print('I am sorry, I don\'t have that in my dictionary.')
        print('')
    
        
while True:
    print('Welcome to the Greek Practice Program!')
    print('')
    print('What would you like to do?')
    print('')
    print('[Practice] [Translate] [Exit]')
    print('')
    optionSelection = input().strip().lower()
        
    if optionSelection != 'practice' and optionSelection != 'translate' and \
       optionSelection != 'exit':
        print('')
        print('Please select either practice, translate, or exit')
        optionSelection = ''
        print('')

    if optionSelection == 'practice':
        while optionSelection == 'practice':
            practiceGreek()
            print('')
            print('Would you like another? [yes] [no]')
            print('')
            selection = input().strip().lower()
            if selection == 'yes':
                print('')
                continue
            else:
                print('')
                break
                
            
    elif optionSelection == 'translate':
        while optionSelection == 'translate':
            translateToGreek()
            print('')
            print('Would you like to translate another phrase? [yes] [no]')
            print('')
            selection = input().strip().lower()
            if selection == 'yes':
                print('')
                continue
            else:
                print('')
                break
        
    
    elif optionSelection == 'exit':
        print('')
        print('Thank you for using the Greek Practice Program!')
        print('')
        sys.exit()

7
8
 
 

Hi, I recently realised one can use immutable default arguments to avoid a chain of:

def append_to(element, to=None):
    if to is None:
        to = []

at the beginning of each function with default argument for set, list, or dict.

9
 
 

Hello.

I recently updated my "Practice Python Projects" ebook, which presents five beginner-to-intermediate level projects inspired by real world use cases.

You can read it online here: https://learnbyexample.github.io/practice_python_projects/preface.html

Or, you can get pdf/epub versions via https://learnbyexample.gumroad.com/l/py_projects/free (free till this weekend).

More resources related to projects: https://learnbyexample.github.io/py_resources/beginners.html#projects

Happy learning :)

10
11
12
 
 

I'm looking to learn about this language from a technical level, and any searches I do on today's search engines is just going to return guides to writing Python code, which is not what I want.

I understand how C++ works. For example, I know that virtual functions are stored as a trap table in an object's instance, and the function is wrapped around something that decodes that trap table from this object instance.

I'm wondering if there's something that goes into that level of technicality with python. For example, I would want to know how function declarations (and re-declarations) work in python. Is the bytecode stored as a heap object which can be freed just as a regular heap object? Is it a map of strings within the current stack context? How does creating a thread handle it?

13
14
 
 

This is a question for people more experienced with Python, but everybody feel free to answer if you feel like you can provide something decent to the discussion.

Also feel free to explain why you feel that way and your experiences with Python and the paradigms.

15
 
 

Example script: https://gist.github.com/thingsiplay/ae9a26322cd5830e52b036ab411afd1f

Hi all. I just wanted to share a way to handle a so called advanced help menu, where additional options are listed that are otherwise hidden with regular help. Hidden options should still function. This is just to have less clutter in normal view.

I've researched the web to see how people does it, and this is the way I like most so far. If you think this is problematic, please share your thoughts. This is for a commandline terminal application, that could also be automated through a script.

How it works on a high level

Before the ArgumentParser() is called, we check the sys.argv for the trigger option --advanced-help. Depending on this we set a variable to true or false. Then with the setup of the parser after the ArgumenParser() call, we add the --advanced-help option to the list of regular help.

advanced_help = False
for arg in sys.argv:
    if arg == "--":
        break
    if arg == "--advanced-help":
        advanced_help = True

parser = argparse.ArgumentParser()

Continue setting up your options as usual. But for the help description of those you want to exclude when using just regular -h, add an inline if else statement (ternary statement). This statement will put the help description only if advanced_help variable is true, otherwise it puts argparse.SUPPRESS to hide the option. Do this with all the options you want to hide.

parser.add_argument(
    "-c",
    "--count",
    action="store_true",
    default=False,
    help="print only a count of matching items per list, output file unaffected"
    if advanced_help
    else argparse.SUPPRESS,
)

At last we need to actually parse what you just setup. For this we need to assign our custom list, that is based on the sys.argv, plus the regular --help option. This way we can use --advanced-help without the need for -h or --help in addition to show any help message.

if advanced_help:
    args = parser.parse_args(sys.argv[0:0] + ["--help"] + sys.argv[1:])
else:
    args = parser.parse_args()

Run following program once with ./thing.py -h and ./thing.py --advanced-help.

16
17
18
19
20
 
 

I ran into this at local Python meetup yesterday. Made with Python and asyncssh. Fun project and also a joke as well as commentary about current state of the social media

21
22
23
24
 
 

I'm finding myself with a couple of really big databases and my PC is throwing memory errors so I'm moving the project to polars and learning on the way in, and would like to read your experience in how you did it, what frustrate you and what you found good (I'm still getting used with the syntax, but I'm loving how fast it reads the databases)

25
view more: next ›