Reuven Lerner: Improve your “pandas” skills with “Pandas Workout”(17 hours, 20 minutes ago)

As you might know, I’ve been working lately on my new book, Pandas Workout, with 50 exercises to improve your fluency using the “pandas” library for data analysis.

Well, I have exciting news: The book is now available as a MEAP, aka the “Manning Early Access Program.” This means that if you buy the book now, you’ll have access to the chapters as they’re written.

The text needs further editing, as well as technical reviews, graphics, diagrams, indexing, and the like. So it’s not done. But it’s definitely in good enough shape to start improving your “pandas” chops, allowing you to understand how the library works and how to use it better.

Also: The “50 exercises” description is a bit incorrect: Every exercise has three “Beyond the exercise” problems, taking the existing question to the next level or asking you to perform a related task. So when I say “50 exercises,” I really mean, “200 exercises.” But hey, what’s a factor of 4 among friends?

Even better: I’ve created Jupyter notebooks for all of the exercise solutions, including the “beyond” exercises — so you can download and experiment with those on your own computer.

But wait, there’s more!

To celebrate the release of this MEAP, Manning has provided a 50% discount. Just use the coupon code “mllerner250” at checkout.

You can get a copy of Pandas Workout at https://PandasWorkout.com/.

And hey, while you’re at it — you can also check out Python Workout, at https://PythonWorkout.com/.

Questions? Just e-mail me at reuven@lerner.co.il, or hit me up on Twitter as @reuvemmlerner.

And now? It’s time to get back to writing…

The post Improve your “pandas” skills with “Pandas Workout” appeared first on Reuven Lerner.

Python Bytes: #245 Fire up your Python time machine (and test some code)(21 hours, 25 minutes ago)

<p><strong>Watch the live stream:</strong></p> <a href='https://www.youtube.com/watch?v=4tgVdjdULzI' style='font-weight: bold;'>Watch on YouTube</a><br> <br> <p><strong>About the show</strong></p> <p>Sponsored by <strong>us:</strong></p> <ul> <li>Check out the <a href="https://training.talkpython.fm/courses/all"><strong>courses over at Talk Python</strong></a></li> <li>And <a href="https://pythontest.com/pytest-book/"><strong>Brian’s book too</strong></a>!</li> </ul> <p>Special guest: Juan Pedro Araque Espinosa (Youtube Chanel: <a href="https://www.youtube.com/channel/UCLpaX8JBrJTRBy0R9IM9W7A">Commit that Line</a>)</p> <p><strong>Michael #1:</strong> <a href="https://www.jetbrains.com/lp/devecosystem-2021/"><strong>State of the community (via Jet Brains)</strong></a></p> <ul> <li>This report presents the combined results of the fifth annual Developer Ecosystem Survey conducted by JetBrains</li> <li>Not just Python, but all of us</li> <li>Python is more popular than Java in terms of overall usage, while Java is more popular than Python as a main language.</li> <li>The 5 fastest growing languages are Python, TypeScript, Kotlin, SQL, and Go.</li> <li>A majority of the respondents (71%) develop for web backend.</li> <li>Does fall into the trap of “Hi, I’m a CSS developer, nice to meet you” though</li> <li>Women are more likely than men to be involved in data analysis, machine learning, and UX/UI design or research. </li> <li>Women are less likely than men to be involved in infrastructure development and DevOps, system administration, or Deployment.</li> </ul> <p><strong>Brian #2:</strong> <a href="https://pypi.org/project/cornell/"><strong>Cornell - record &amp; replay mock server</strong></a></p> <ul> <li>Suggested by Yael Mintz (and it’s her project)</li> <li><a href="https://medium.com/hiredscore-engineering/scale-up-your-e2e-tests-using-mock-server-a6872f660288">Introduction blog post</a> <ul> <li>“Cornell makes it dead simple, via its record and replay features to perform end-to-end testing in a fast and isolated testing environment.</li> <li>When your application integrates with multiple web-based services, end-to-end testing is crucial before deploying to production. Mocking is often a tedious task. It becomes even more tiresome when working with multiple APIs from multiple vendors.</li> <li><a href="https://github.com/kevin1024/vcrpy">vcrpy</a> is an awesome library that records and replays HTTP interactions for unit tests. Its output is saved to reusable "cassette" files.</li> <li>By wrapping vcrpy with Flask, Cornell provides a lightweight record and replay server that can be easily used during distributed system testing and simulate all HTTP traffic needed for your tests.”</li> </ul></li> </ul> <p><strong>Juanpe</strong> <strong>#3:</strong> <a href="https://github.com/FactoryBoy/factory_boy"><strong>Factory boy</strong></a> <strong>(with Pydantic by chance)</strong></p> <ul> <li><code>Factory_boy</code> allows creating factories to generate objects that could be used as text fixtures</li> <li>Briefly mentioned in the past in <a href="https://pythonbytes.fm/episodes/show/193/break-out-the-django-testing-toolbox">episode 193</a></li> <li>A factory takes a base object and allows to very easily and naturally define default values for each field of the object. </li> <li>One can have many factories for the same object that could be used define different types of fixtures of the same object</li> <li>It works with ORM objects (Django, Mongo, SQLAlchemy…)</li> <li>If you have a project that uses Pydantic to define your objects, factory boy also supports Pydantic although it is not documented and does it by a side effect</li> <li>Internally factory boy generates a parameters dictionary that that is unpacked when constructing the model at hands. This works perfectly with pydantic and can be used to generate pydantic objects on the fly with the full power of factory boy <a href="https://github.com/FactoryBoy/factory_boy"></a></li> </ul> <p><strong>Michael #4:</strong> <a href="https://github.com/joerick/pyinstrument"><strong>pyinstrument</strong></a></p> <ul> <li>Call stack profiler for Python. Shows you why your code is slow! </li> <li>Instead of writing <code>python script.py</code>, type <code>pyinstrument script.py</code> </li> <li>Your script will run as normal, and at the end (or when you press <code>^C</code>), Pyinstrument will output a colored summary showing where most of the time was spent.</li> <li>Async support! Pyinstrument now detects when an async task hits an await, and tracks time spent outside of the async context under this await.</li> <li>Pyinstrument also has a Python API. Just surround your code with Pyinstrument</li> <li>Nice middleware examples for Flask &amp; Django</li> </ul> <p><strong>Brian #5:</strong> <a href="https://www.python.org/downloads/release/python-3100rc1/"><strong>Python 3.10 is now in Release Candidate phase. RC1 just released.</strong></a></p> <ul> <li>RC2 planned for 2021-09-06</li> <li>official release is planned for 2021-10-04</li> <li>It is <strong>strongly encourage</strong> maintainers of third-party Python projects to prepare their projects for 3.10 compatibility during this phase</li> <li>Reminder of major changes: <ul> <li><a href="https://www.python.org/dev/peps/pep-0623/">PEP 623</a> -- Deprecate and prepare for the removal of the wstr member in PyUnicodeObject.</li> <li><a href="https://www.python.org/dev/peps/pep-0604/">PEP 604</a> -- Allow writing union types as X | Y</li> <li><a href="https://www.python.org/dev/peps/pep-0612/">PEP 612</a> -- Parameter Specification Variables</li> <li><a href="https://www.python.org/dev/peps/pep-0626/">PEP 626</a> -- Precise line numbers for debugging and other tools.</li> <li><a href="https://www.python.org/dev/peps/pep-0618/">PEP 618</a> -- Add Optional Length-Checking To zip.</li> <li><a href="https://bugs.python.org/issue12782">bpo-12782</a>: Parenthesized context managers are now officially allowed.</li> <li><a href="https://www.python.org/dev/peps/pep-0632/">PEP 632</a> -- Deprecate distutils module.</li> <li><a href="https://www.python.org/dev/peps/pep-0613/">PEP 613</a> -- Explicit Type Aliases</li> <li><a href="https://www.python.org/dev/peps/pep-0634/">PEP 634</a> -- Structural Pattern Matching: Specification</li> <li><a href="https://www.python.org/dev/peps/pep-0635/">PEP 635</a> -- Structural Pattern Matching: Motivation and Rationale</li> <li><a href="https://www.python.org/dev/peps/pep-0636/">PEP 636</a> -- Structural Pattern Matching: Tutorial</li> <li><a href="https://www.python.org/dev/peps/pep-0644/">PEP 644</a> -- Require OpenSSL 1.1.1 or newer</li> <li><a href="https://www.python.org/dev/peps/pep-0624/">PEP 624</a> -- Remove Py_UNICODE encoder APIs</li> <li><a href="https://www.python.org/dev/peps/pep-0597/">PEP 597</a> -- Add optional EncodingWarning</li> </ul></li> </ul> <p><strong>Juanpe</strong> <strong>#6:</strong> <a href="https://github.com/adamchainz/time-machine"><strong>time-machine</strong></a></p> <ul> <li>Time-machine mock datetime and time related calls globally noticeably faster than other well known tools like freezgun.</li> <li>The mocking is achieved by replacing the c-level calls by whatever value we want which means the library does not need to mock individual imports.</li> <li>Mocking datetime cannot be done with patch.object and needs to be patched everywhere it is used which can turn mocking everything into a tedious (and/or slow) process.</li> <li>Datetime methods (now, today, utcnow…) can be mocked by setting a frozen time or by letting the time tick since the mock call is made.</li> <li>It provides a simple context manager to use it as well as pytest fixture that makes using it very simple</li> </ul> <pre><code> from datetime import datetime import time_machine @time_machine.travel("2021-01-01 21:00") def test_in_the_past(): assert datetime.now() == datetime(2021, 1, 1, 21, 0) --------------------------------- # The time_machine fixture can also be used with pytest def test_in_the_past(time_machine): time_machine.move_to(datetime(2021, 1, 1, 21, 0)) assert datetime.now() == datetime(2021, 1, 1, 21, 0) </code></pre> <p><strong>Extras</strong></p> <p>Michael</p> <ul> <li><a href="https://www.techradar.com/news/credit-card-stealing-malware-found-in-official-python-repository">Credit-card stealing malware found in official Python repository</a> and <a href="https://arstechnica.com/gadgets/2021/07/malicious-pypi-packages-caught-stealing-developer-data-and-injecting-code/">Software downloaded 30,000 times from PyPI ransacked developers’ machines</a> (via Joe Riedly)</li> </ul> <p>Brian</p> <ul> <li><a href="https://testandcode.com/162">Flavors of TDD - Test &amp; Code episode 162</a></li> <li>Working on tox and CI chapter of <a href="https://pragprog.com/titles/bopytest2/python-testing-with-pytest-second-edition/">2nd edition of pytest book</a>, hoping that to be released within the next week.</li> </ul> <p><strong>Joke</strong> </p> <p><a href="https://twitter.com/darkgaro/status/1421208437480906752">JavaScript Developer Bouncing from framework to framework</a></p>

Podcast.__init__: Delivering Deep Learning Powered Speech Recognition As A Service For Developers At AssemblyAI(1 day, 4 hours ago)

Building a software-as-a-service (SaaS) business is a fairly well understood pattern at this point. When the core of the service is a set of machine learning products it introduces a whole new set of challenges. In this episode Dylan Fox shares his experience building Assembly AI as a reliable and affordable option for automatic speech recognition that caters to a developer audience. He discusses the machine learning development and deployment processes that his team relies on, the scalability and performance considerations that deep learning models introduce, and the user experience design that goes into building for a developer audience. This is a fascinating conversation about a unique cross-section of considerations and how Dylan and his team are building an impressive and useful service.

Summary

Building a software-as-a-service (SaaS) business is a fairly well understood pattern at this point. When the core of the service is a set of machine learning products it introduces a whole new set of challenges. In this episode Dylan Fox shares his experience building Assembly AI as a reliable and affordable option for automatic speech recognition that caters to a developer audience. He discusses the machine learning development and deployment processes that his team relies on, the scalability and performance considerations that deep learning models introduce, and the user experience design that goes into building for a developer audience. This is a fascinating conversation about a unique cross-section of considerations and how Dylan and his team are building an impressive and useful service.

Announcements

  • Hello and welcome to Podcast.__init__, the podcast about Python’s role in data and science.
  • When you’re ready to launch your next app or want to try a project you hear about on the show, you’ll need somewhere to deploy it, so take a look at our friends over at Linode. With the launch of their managed Kubernetes platform it’s easy to get started with the next generation of deployment and scaling, powered by the battle tested Linode platform, including simple pricing, node balancers, 40Gbit networking, dedicated CPU and GPU instances, and worldwide data centers. Go to pythonpodcast.com/linode and get a $100 credit to try out a Kubernetes cluster of your own. And don’t forget to thank them for their continued support of this show!
  • Your host as usual is Tobias Macey and today I’m interviewing Dylan Fox about AssemblyAI, a powerful and easy to use speech recognition API designed for developers

Interview

  • Introductions
  • How did you get introduced to Python?
  • Can you describe what Assembly AI is and the story behind it?
  • Speech recognition is a service that is being added to every cloud platform, video service, and podcast product. What do you see as the motivating factors for the current growth in this industry?
    • How would you characterize your overall position in the market?
  • What are the core goals that you are focused on with AssemblyAI?
  • Can you describe the different ways that you are using Python across the company?
  • How is the AssemblyAI platform architected?
    • What are the complexities that you have to work around to maintain high uptime for an API powered by a deep learning model?
    • What are the scaling challenges that crop up, whether on the training or serving?
  • What are the axes for improvement for a speech recognition model?
    • How do you balance tradeoffs of speed and accuracy as you iterate on the model?
  • What is your process for managing the deep learning workflow?
  • How do you manage CI/CD for your deep learning models?
  • What are the open areas of research in speech recognition?
  • What are the most interesting, innovative, or unexpected ways that you have seen AssemblyAI used?
  • What are the most interesting, unexpected, or challenging lessons that you have learned while working on AssemblyAI?
  • When is AssemblyAI the wrong choice?
  • What do you have planned for the future of AssemblyAI?

Keep In Touch

Picks

Closing Announcements

  • Thank you for listening! Don’t forget to check out our other show, the Data Engineering Podcast for the latest on modern data management.
  • Visit the site to subscribe to the show, sign up for the mailing list, and read the show notes.
  • If you’ve learned something or tried out a project from the show then tell us about it! Email hosts@podcastinit.com) with your story.
  • To help other people find the show please leave a review on iTunes and tell your friends and co-workers
  • Join the community in the new Zulip chat workspace at pythonpodcast.com/chat

Links

The intro and outro music is from Requiem for a Fish The Freak Fandango Orchestra / CC BY-SA

Python⇒Speed: NumPy views: saving memory, leaking memory, and subtle bugs(1 day, 5 hours ago)

If you’re using Python’s NumPy library, it’s usually because you’re processing large arrays that use plenty of memory. To reduce your memory usage, chances are you want to minimize unnecessary copying,

NumPy has a built-in feature that does this transparently, in many common cases: memory views. However, this feature can also cause higher memory usage by preventing arrays from being garbage collected. And in some cases it can cause bugs, with data being mutated in unexpected ways.

To avoid these problems, let’s learn how views work and the implications for your code.

Read more...

PyCoder’s Weekly: Issue #484 (Aug. 3, 2021)(1 day, 9 hours ago)

#484 – AUGUST 3, 2021
View in Browser »

The PyCoder’s Weekly Logo


Python and REST APIs: Interacting With Web Services

In this tutorial, you’ll learn how to use Python to communicate with REST APIs. You’ll learn about REST architecture and how to use the requests library to get data from a REST API. You’ll also explore different Python tools you can use to build REST APIs.
REAL PYTHON

Launchpad Now Runs on Python 3

Python 2 was sunsetted over a year ago, but many folks still find themselves maintaining large Python 2 codebases. The Launchpad team recently finished porting their entire codebase to Python 3, and this article reflects on that process, discusses some of the difficulties they encountered, regressions that occurred, and provides a number of lessons they learned throughout the process. If you are in a position of porting a Python 2 codebase to Python 3, definitely check this out.
COLIN WATSON

Monitor Errors & Performance in your Python Apps = Keep Users Happy

alt

For software teams, monitoring code health is essential. From Error tracking to Performance monitoring, Sentry helps developers see clearer, solve quicker, and learn continuously about their applications - from frontend to backend. Try Sentry for free → with code: PYCODERS
SENTRY sponsor

PEP 665: Specifying Installation Requirements for Python Projects

There’s a new PEP in town, and this one deals with improving how installation requirements are specified in Python projects. The PEP is still in Draft status.
PYTHON.ORG

Twisted 21.7.0 Released

TWISTEDMATRIX.COM

Django Bugfix Release: 3.2.6

DJANGO SOFTWARE FOUNDATION

Discussions

Do Coders Really Learn How to Use Entire Libraries Just From the Documentation?

How do you learn a new library? Do you start with the docs? What do you do if the documentation is lacking? Or do you first search for video lessons or written tutorials?
REDDIT

Python Jobs

Backend Software Engineer (Remote)

Catalpa International

Python Developer (Remote)

Tessian

Software Developer (Remote)

Univention GmbH

Backend Software Engineer (Washington, D.C., USA)

Quorum

Senior Cloud Platform Engineer (Berlin, Germany)

Apheris

Software Engineer (Remote)

Close

Backend Software Engineer (Remote)

Tessian

Python Web Developer (Remote)

Premiere Digital Services

More Python Jobs >>>

Articles & Tutorials

Python’s ChainMap: Manage Multiple Contexts Effectively

In this step-by-step tutorial, you’ll learn about Python’s ChainMap and how to use it to group multiple dictionaries together and manage them as a single one. ChainMap is handy when you need to manage multiple scopes and contexts and define access priorities.
REAL PYTHON

Handling 100 Requests Per Second With Python & Django

The folks over at Ethical Ads recently broke their ads out of the codebase for Read the Docs, where it had been served from a Django app as part of the Read the Docs code line up until 2019. They decided to use Python and Django for their application since the team already knew that stack well. This article compares the performance of hosting services and explains how they stress-tested their application to ensure the best performance at the right cost.
DAVID FISCHER

PyCharm 2021.2 is Out With Built-In Support For Some Cool New Python 3.10 Features

alt

Get hands-on with learning about the new Structural Pattern Matching. PyCharm’s support for Python 3.10 will help you avoid unexpected errors and quickly get to grips with them. If you are as excited about Python 3.10, use the code PYCODERS21 to get 3 free months of PyCharm Professional →
JETBRAINS sponsor

Start Using a Debugger With Your Python Code

Are you still sprinkling print statements throughout your code while writing it? Print statements are often clunky and offer only a limited view of the state of your code. Have you thought there must be a better way? This week on the Real Python Podcase, Nina Zakharenko discusses her conference talk titled “Goodbye Print, Hello Debugger.”
REAL PYTHON podcast

Replit.web: A Python Framework With Built-in Database and Auth Support

The folks over at replit have released a new Python web framework with built-in authentication and database support and, more interestingly, hosting. In a few lines of code, you can have a Python web app connected to a database, authenticating users, and hosted on replit. This could be a great tool for quickly building and hosting prototypes or experimental projects.
SPENCER POGORZELSKI

Monitor Your Home’s Temperature and Humidity With Raspberry Pis and Prometheus

Do you enjoy collecting and analyzing data, or are you looking for a fun project to improve your data skills? Do you also enjoy tinkering with hardware? Then this project might be a fun one for you to check out! Learn how to set up a RaspberryPi using Prometheus to collect and monitor temperature sensor data.
CHRIS COLLINS

Cheat Sheet: 9 Python Security Best Practices

Tip #1: Avoid PyYAML vulnerabilities by using yaml.SafeLoader() instead of yaml.Loader(). Learn 8 more tips in the Python security cheat sheet.
SNYK.IO sponsor

Using sleep() to Code a Python Uptime Bot

Learn how to add time delays to your Python programs. You’ll use the built-in time module to add Python sleep() calls to your code. To practice, you’ll use time.sleep() when making an uptime bot that checks whether a website is still live.
REAL PYTHON course

How to Dockerize Django in 5 Minutes

This short yet informative tutorial explains how to Dockerize a Django application. The tutorial clocks in at less than a 10 minute read, but still finds time to explain why you should consider using Docker in your Django projects.
MATTHEW FREIRE

Projects & Code

prometheus: The Prometheus Monitoring System and Time Series Database

GITHUB.COM/PROMETHEUS

BirdNET: Soundscape Analysis With BirdNET

GITHUB.COM/KAHST

python-launcher: Python Launcher for Unix

GITHUB.COM/BRETTCANNON

connector-x: Fastest Library to Load Data From DB to DataFrames in Rust and Python

GITHUB.COM/SFU-DB

Events

Real Python Office Hours (Virtual)

August 4, 2021
REALPYTHON.COM

PyCon India 2021 (Virtual)

September 17 – 20, 2021
PYCON.ORG


Happy Pythoning!
This was PyCoder’s Weekly Issue #484.
View in Browser »

alt

[ Subscribe to 🐍 PyCoder’s Weekly 💌 – Get the best Python news, articles, and tutorials delivered to your inbox once a week >> Click here to learn more ]

Test and Code: 162: Flavors of TDD(1 day, 10 hours ago)

What flavor of TDD do you practice?

In this episode we talk about:

  • Classical vs Mockist TDD
  • Detroit vs London (I actually refer to it in the episode as Chicago instead of Detroit. Oh well.)
  • Static vs Behavior
  • Inside Out vs Outside In
  • Double Loop TDD
  • BDD
  • FDD
  • Tracer Bullets
  • Rules of TDD
  • Team Structure
  • Lean TDD

This is definitely an episode I'd like feedback on. Reach out to me @brianokken or via the contact form for further questions or if I missed some crucial variant of TDD that you know and love.

Sponsored By:

Support Test & Code

Links:

<p>What flavor of TDD do you practice? </p> <p>In this episode we talk about:</p> <ul> <li>Classical vs Mockist TDD</li> <li>Detroit vs London (I actually refer to it in the episode as Chicago instead of Detroit. Oh well.)</li> <li>Static vs Behavior</li> <li>Inside Out vs Outside In</li> <li>Double Loop TDD</li> <li>BDD</li> <li>FDD</li> <li>Tracer Bullets</li> <li>Rules of TDD</li> <li>Team Structure</li> <li>Lean TDD </li> </ul> <p>This is definitely an episode I&#39;d like feedback on. Reach out to me <a href="https://twitter.com/brianokken" rel="nofollow">@brianokken</a> or via the <a href="https://testandcode.com/contact" rel="nofollow">contact form</a> for further questions or if I missed some crucial variant of TDD that you know and love.</p><p>Sponsored By:</p><ul><li><a href="https://testandcode.com/pycharm" rel="nofollow">PyCharm Professional</a>: <a href="https://testandcode.com/pycharm" rel="nofollow">Try PyCharm Pro for 4 months and learn how PyCharm will save you time.</a> Promo Code: TESTANDCODE21</li></ul><p><a href="https://www.patreon.com/testpodcast" rel="payment">Support Test & Code</a></p><p>Links:</p><ul><li><a href="https://martinfowler.com/articles/mocksArentStubs.html" title="Mocks Aren't Stubs - Martin Fowler" rel="nofollow">Mocks Aren't Stubs - Martin Fowler</a></li><li><a href="https://www.thoughtworks.com/en-us/insights/blog/mockists-are-dead-long-live-classicists?utm_source=pocket_mylist" title="Mockists Are Dead. Long Live Classicists." rel="nofollow">Mockists Are Dead. Long Live Classicists.</a></li><li><a href="http://coding-is-like-cooking.info/2013/04/outside-in-development-with-double-loop-tdd/" title="Double Loop TDD" rel="nofollow">Double Loop TDD</a></li><li><a href="https://en.wikipedia.org/wiki/Behavior-driven_development" title="BDD: Behavior-driven development" rel="nofollow">BDD: Behavior-driven development</a></li><li><a href="https://en.wikipedia.org/wiki/Feature-driven_development" title="FDD: Feature-driven development" rel="nofollow">FDD: Feature-driven development</a></li><li><a href="https://pythontest.com/agile/is-tdd-dead/" title="My reaction to “Is TDD Dead?” - pythontest.com" rel="nofollow">My reaction to “Is TDD Dead?” - pythontest.com</a></li><li><a href="https://pythontest.com/agile/test-first-programming/" title="Test First Programming / Test First Development" rel="nofollow">Test First Programming / Test First Development</a></li><li><a href="https://essenceoftesting.blogspot.com/2018/03/test-driven-development-tdd-and-its-variations.html?utm_source=pocket_mylist" title="Humorous list of TDD variants" rel="nofollow">Humorous list of TDD variants</a> &mdash; BDD = Buzzword Driven Development, CDD = Calendar Driven Development, etc</li></ul>

Python for Beginners: Absolute value of a number in Python(1 day, 13 hours ago)

While working with numbers in python,we need to compare the magnitude of two numbers irrespective of their sign. For example, Magnitude of -10 is greater than magnitude of 1. But when -10 and 1 is compared, 1 is declared as greater number due to its positive sign. To compare the magnitude of the two numbers, first we need to find the absolute value of  the numbers. Then we can compare the absolute values to compare the magnitude of the numbers. In this article, we will implement programs in python to find the absolute value of different numeric data types.

How to calculate the absolute value of a number in Python?

We can calculate the absolute value of any number in python using the abs() function. The abs() function takes a number as its only argument and returns the absolute value of the number.

The input argument can be a floating point number, an integer or a complex number. We can also pass a binary number, an octal number or a hexadecimal number as input to abs() function.

We can understand the working of the abs() function from the examples in the following section.

Examples using abs() function in Python

We can find an absolute value of an integer using the abs() function as follows.

myNum=10
absoluteVal=abs(myNum)
print("Absolute value of {} is {}.".format(myNum,absoluteVal))
myNum=-10
absoluteVal=abs(myNum)
print("Absolute value of {} is {}.".format(myNum,absoluteVal))

Output:

Absolute value of 10 is 10.
Absolute value of -10 is 10.

We can find the absolute value of a floating point number using the abs() function as follows.

myNum=10.5
absoluteVal=abs(myNum)
print("Absolute value of {} is {}.".format(myNum,absoluteVal))
myNum=-10.5
absoluteVal=abs(myNum)
print("Absolute value of {} is {}.".format(myNum,absoluteVal))

Output:

Absolute value of 10.5 is 10.5.
Absolute value of -10.5 is 10.5.

If we want to find the magnitude of a complex number, we can do it using the abs() function. The abs() function takes a complex number as input and returns the magnitude of the complex number as follows.

myNum=3+5j
absoluteVal=abs(myNum)
print("Absolute value of {} is {}.".format(myNum,absoluteVal))

Output:

Absolute value of (3+5j) is 5.830951894845301.

We can also determine the absolute value of a number in the decimal number system using the abs() function if the number has been represented in a binary, octal or hexadecimal number system as follows.

#hexadecimal number
myNum=0x123
absoluteVal=abs(myNum)
print("Absolute value {} is {}.".format(myNum,absoluteVal))
#binary number
myNum=0b1001
absoluteVal=abs(myNum)
print("Absolute value of {} is {}.".format(myNum,absoluteVal))
#octal number
myNum=0o123
absoluteVal=abs(myNum)
print("Absolute value of {} is {}.".format(myNum,absoluteVal))

Output:

Absolute value 291 is 291.
Absolute value of 9 is 9.
Absolute value of 83 is 83.

Handling errors during calculation of absolute value

Python is a programming language with dynamic typing. It means that the python interpreter determines the data type of a variable at the runtime. Due to this, it is possible that when we pass a variable as input to the abs() function, it may not be having value with the correct data type to produce the correct output. For example, when we pass a string as input argument to the abs() function, The function will raise a TypeError exception as follows.

myNum="PFB"
absoluteVal=abs(myNum)
print("Absolute value {} is {}.".format(myNum,absoluteVal))

Output:

Traceback (most recent call last):
  File "/home/aditya1117/PycharmProjects/pythonProject/main.py", line 2, in <module>
    absoluteVal=abs(myNum)
TypeError: bad operand type for abs(): 'str'

We know that when any part of a program raises an exception, the program is terminated immediately . This will result in loss of data written to the file or any significant calculation performed in the program.We can avoid this loss by using exception handling using python try except blocks. The abs() function raises an exception whenever we pass a variable with an incorrect type as input argument to the function. We can handle the exception and save necessary data and close the files by in the except block if needed.

Conclusion

In this article, We have studied about using abs() function in python to find absolute values of numbers. We have also studied how to find the absolute value of numbers in binary, octal and hexadecimal number system in decimal number system. Finally, we saw how to handle any exception generated by the abs() function using try except blocks. Stay tuned for more informative articles.

The post Absolute value of a number in Python appeared first on PythonForBeginners.com.

Python Morsels: Making a read-only attribute(1 day, 15 hours ago)

Transcript

How can we make a read-only attribute in Python?

A property is like an auto-updating attribute

We have a class called Square which accepts a length and an optional color and stores those as length and color attributes:

class Square:
    def __init__(self, length, color=None):
        self.length = length
        self.color = color

    def __repr__(self):
        return f"Square({self.length!r}, {self.color!r})"

    @property
    def area(self):
        return self.length**2

If we make a Square object (with just a length in this case):

>>> s1 = Square(4)

We can see the length and color in the string representation of this Square object:

>>> s1
Square(4, None)

This class also has an area property.

    @property
    def area(self):
        return self.length**2

A property is a kind of like a virtual attribute.

Every time we access the area attribute, a function will be executed and its return value will be given back to us:

>>> s1.area
16

That function call happens automatically, simply by accessing the area attribute.

So if we change the length of a Square object:

>>> s1.length = 3

The area will seem to change automatically:

>>> s1.area
9

Properties can make read-only attributes

What if we wanted to make it so the color of our Square objects can be changed but the length and area can't be changed?

>>> s1.color = 'purple'
>>> s1.color
'purple'

We want to make the length and the area attributes read-only.

It turns out the area attribute is already read-only:

>>> s1.area = 100
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: can't set attribute

We can't assign to area because properties are read-only by default.

We could try to make our length attribute into a property, by adding this to our class definition:

    @property
    def length(self):
        return self.length

We're using the property decorator to create a property named length and this property returns the length attribute when accessed.

This length property doesn't quite work though:

>>> s1 = Square(4)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/trey/shapes.py", line 3, in __init__
    self.length = length
AttributeError: can't set attribute

It doesn't work because in our initializer method we assigned to length:

    def __init__(self, length, color=None):
        self.length = length
        self.color = color

But length is a property that doesn't have a setter, so it's read-only (all properties are read-only by default).

Our property is accessing data that's stored in the same places as our property. That's not possible! There's nothing to distinguish our property name from an attribute of the same name, so we have a name collision.

We need our property name to be different from the attribute where we actually store our data. We don't want to rename our property, so let's rename our attribute.

Using an underscore prefix for internal attributes

We need an attribute that has a different name than length.

When you have an attribute that represents internal data that shouldn't be accessed directly (by code outside of your class) it's common in Python to prefix a single underscore (_) before that attribute name.

PEP 8 notes this convention as well: "Use one leading underscore only for non-public methods and instance variables."

So we'll rename the attribute that stores our length to _length: So, we'll say:

    def __init__(self, length, color=None):
        self._length = length
        self.color = color

And our property will access self._length now to get the length:

    @property
    def length(self):
        return self._length

Here's the full class:

class Square:
    def __init__(self, length, color=None):
        self._length = length
        self.color = color

    def __repr__(self):
        return f"Square({self.length!r}, {self.color!r})"

    @property
    def area(self):
        return self.length**2

    @property
    def length(self):
        return self._length

Now when we make a Square object, we'll see that there is a length:

>>> s1 = Square(4)
>>> s1.length
4

But we can't assign to it because it's a property:

>>> s1.length = 3
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: can't set attribute

The single underscore prefix is just a convention

Note that this single underscore prefix is just a convention. So we can still access the _length attribute if we want to:

>>> s1._length
4

And in fact we can even change it:

>>> s1._length = 5

Which changes the length on our Square object:

>>> s1.length
5

But when other Python programmers see an assignment to an underscore-prefixed attribute, they'll look at that code and think something strange is going on: we're changing some internal details of an object. An underscore-prefixed attribute is supposed to be private by convention, so it's uncommon to see an assignment to an underscore-prefixed attribute.

Summary

If you need to make a read-only attribute in Python, you can turn your attribute into a property that delegates to an attribute with almost the same name, but with an underscore prefixed before the its name to note that it's private convention.

Real Python: Using sleep() to Code a Python Uptime Bot(1 day, 15 hours ago)

Have you ever needed to make your Python program wait for something? You might use a Python sleep() call to simulate a delay in your program. Perhaps you need to wait for a file to upload or download, or for a graphic to load or be drawn to the screen. You might even need to pause between calls to a web API, or between queries to a database. Adding Python sleep() calls to your program can help in each of these cases, and many more!

In this course, you’ll learn:

  • The basics of time.sleep()
  • How you can use timeit to measure your code’s execution time
  • How to use time.sleep() to build an uptime bot

[ Improve Your Python With 🐍 Python Tricks 💌 – Get a short & sweet Python Trick delivered to your inbox every couple of days. >> Click here to learn more and see examples ]

Python Insider: Python 3.10.0rc1 is available(1 day, 16 hours ago)

Python 3.10.0 is almost ready. This release, 3.10.0rc1, is the penultimate release preview. You can get it here:

https://www.python.org/downloads/release/python-3100rc1/

This release, **3.10.0rc1**, is the penultimate release preview.  Entering the release candidate phase, only reviewed code changes which are
clear bug fixes are allowed between this release candidate and the final release. The second candidate and the last planned release preview is
currently planned for 2021-09-06 while the official release is planned for 2021-10-04.

There will be no ABI changes from this point forward in the 3.10 series and the goal is that there will be as few code changes as possible.

Call to action

Core developers: all eyes on the docs now

  • Are all your changes properly documented?
  • Did you notice other changes you know of to have insufficient documentation?

Community members

We strongly encourage maintainers of third-party Python projects to prepare their projects for 3.10 compatibilities during this phase. As always, report any issues to the Python bug tracker.

Please keep in mind that this is a preview release and its use is **not** recommended for production environments.

Major new features of the 3.10 series, compared to 3.9

Many new features for Python 3.10 are still being planned and written. Among the new major new features and changes so far:

  • PEP 623 – Deprecate and prepare for the removal of the wstr member in PyUnicodeObject.
  • PEP 604 – Allow writing union types as X | Y
  • PEP 612 – Parameter Specification Variables
  • PEP 626 – Precise line numbers for debugging and other tools.
  • PEP 618 – Add Optional Length-Checking To zip.
  • bpo-12782: Parenthesized context managers are now officially allowed.
  • PEP 632 – Deprecate distutils module.
  • PEP 613 – Explicit Type Aliases
  • PEP 634 – Structural Pattern Matching: Specification
  • PEP 635 – Structural Pattern Matching: Motivation and Rationale
  • PEP 636 – Structural Pattern Matching: Tutorial
  • PEP 644 – Require OpenSSL 1.1.1 or newer
  • PEP 624 – Remove Py_UNICODE encoder APIs
  • PEP 597 – Add optional EncodingWarning
  • (Hey, fellow core developer, if a feature you find important is missing from this list, let Pablo know.)

The next pre-release, the second release candidate,  will only be released if needed (scheduled for Monday, 2021-09-06). Otherwise, the next release will directly be the final release of Python 3.10.0, which is currently scheduled for Monday, 2021-10-04.

bpo-38605from __future__ import annotations (PEP 563) used to be on this list in previous pre-releases but it has been postponed to Python 3.11 due to some compatibility concerns. You can read the Steering Council communication about it here to learn more.

More resources

And now for something completely different

In quantum physics, the spin is an intrinsic form of angular momentum carried by elementary particles, composite particles, and atomic nuclei. The spin is one of two types of angular momentum in quantum mechanics, the other being orbital angular momentum. The orbital angular momentum operator is the quantum-mechanical counterpart to the classical angular momentum of orbital revolution and appears when there is periodic structure to its wavefunction as the angle varies. For photons, spin is the quantum-mechanical counterpart of the polarization of light; for electrons, the spin has no classical counterpart.

We hope you enjoy those new releases!

Thanks to all of the many volunteers who help make Python Development and these releases possible! Please consider supporting our efforts by volunteering yourself or through organization contributions to the Python Software Foundation.

Your friendly release team,

Pablo Galindo @pablogsal

Ned Deily @nad

Steve Dower @steve.dower