FLOSS Project Planets

ItsMyCode: [Solved] AttributeError: ‘str’ object has no attribute ‘get’

Planet Python - Wed, 2022-06-22 16:48

The AttributeError: ‘str’ object has no attribute ‘get’ mainly occurs when you try to call the get() method on the string data type. The attribute get() method is present in the dictionary and must be called on the dictionary data type.

In this tutorial, we will look at what exactly is AttributeError: ‘str’ object has no attribute ‘get’ and how to resolve this error with examples.

What is AttributeError: ‘str’ object has no attribute ‘get’?

If we call the get() method on the string data type, Python will raise an AttributeError: ‘str’ object has no attribute ‘get’. The error can also happen if you have a method which returns an string instead of a dictionary.

Let us take a simple example to reproduce this error.

# Method return string instead of dict def fetch_data(): output = "Toyota Car" return output data = fetch_data() print(data.get("name"))

Output

AttributeError: 'str' object has no attribute 'get'

In the above example, we have a method fetch_data() which returns an string instead of a dictionary.

Since we call the get() method on the string type, we get AttributeError.

We can also check if the variable type using the type() method, and using the dir() method, we can also print the list of all the attributes of a given object.

# Method return string instead of dict def fetch_data(): output = "Toyota Car" return output data = fetch_data() print("The type of the object is ", type(data)) print("List of valid attributes in this object is ", dir(data))

Output

The type of the object is <class 'str'> List of valid attributes in this object is ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'removeprefix', 'removesuffix', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill'] How to fix AttributeError: ‘str’ object has no attribute ‘get’?

Let us see how we can resolve the error.

Solution 1 – Call the get() method on valid dictionary

We can resolve the error by calling the get() method on the valid dictionary object instead of the string type.

The dict.get() method returns the value of the given key. The get() method will not throw KeyError if the key is not present; instead, we get the None value or the default value that we pass in the get() method.

# Method returns dict def fetch_data(): output = {"Name": "Audi", "Release_Date": "2022", "Price": "$45000"} return output data = fetch_data() # Get the car Name print(data.get("Name"))

Output

Audi Solution 2 – Check if the object is of type dictionary using type

Another way is to check if the object is of type dictionary; we can do that using the type() method. This way, we can check if the object is of the correct data type before calling the get() method.

# Method returns dict def fetch_data(): output = {"Name": "Audi", "Release_Date": "2022", "Price": "$45000"} return output data = fetch_data() # Check if the object is dict if (type(data) == dict): print(data.get("Name")) softwares = "Norton, Bit Defender" if (type(softwares) == dict): print(softwares.get("Name")) else: print("The object is not dictionary and it is of type ", type(softwares))

Output

Audi The object is not dictionary and it is of type <class 'str'> Solution 3 – Check if the object has get attribute using hasattr

Before calling the get() method, we can also check if the object has a certain attribute. Even if we call an external API which returns different data, using the hasattr() method, we can check if the object has an attribute with the given name.

# Method returns dict def fetch_data(): output = {"Name": "Audi", "Release_Date": "2022", "Price": "$45000"} return output data = fetch_data() # Check if the object has get attribute if (hasattr(data, 'get')): print(data.get("Name"))

Output

Audi Conclusion

The AttributeError: ‘str’ object has no attribute ‘get’ occurs when you try to call the get() method on the string data type. The error also occurs if the calling method returns an string instead of a dictionary object.

We can resolve the error by calling the get() method on the dictionary object instead of an string. We can check if the object is of type dictionary using the type() method, and also, we can check if the object has a valid get attribute using hasattr() before performing the get operation.

Categories: FLOSS Project Planets

ItsMyCode: [Solved] AttributeError: &#8216;float&#8217; object has no attribute &#8216;get&#8217;

Planet Python - Wed, 2022-06-22 16:07

The AttributeError: ‘float’ object has no attribute ‘get’ mainly occurs when you try to call the get() method on the float data type. The attribute get() method is present in the dictionary and must be called on the dictionary data type.

In this tutorial, we will look at what exactly is AttributeError: ‘float’ object has no attribute ‘get’ and how to resolve this error with examples.

What is AttributeError: ‘float’ object has no attribute ‘get’?

If we call the get() method on the float data type, Python will raise an AttributeError: ‘float’ object has no attribute ‘get’. The error can also happen if you have a method which returns an float instead of a dictionary.

Let us take a simple example to reproduce this error.

# Method return float instead of dict def fetch_data(): output = 44.55 return output data = fetch_data() print(data.get("price"))

Output

AttributeError: 'float' object has no attribute 'get'

In the above example, we have a method fetch_data() which returns an float instead of a dictionary.

Since we call the get() method on the float type, we get AttributeError.

We can also check if the variable type using the type() method, and using the dir() method, we can also print the list of all the attributes of a given object.

# Method return float instead of dict def fetch_data(): output = "Toyota Car" return output data = fetch_data() print("The type of the object is ", type(data)) print("List of valid attributes in this object is ", dir(data))

Output

The type of the object is <class 'float'> List of valid attributes in this object is ['__abs__', '__add__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getformat__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__int__', '__le__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__pos__', '__pow__', '__radd__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rmod__', '__rmul__', '__round__', '__rpow__', '__rsub__', '__rtruediv__', '__set_format__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', 'as_integer_ratio', 'conjugate', 'fromhex', 'hex', 'imag', 'is_integer', 'real'] How to fix AttributeError: ‘float’ object has no attribute ‘get’?

Let us see how we can resolve the error.

Solution 1 – Call the get() method on valid dictionary

We can resolve the error by calling the get() method on the valid dictionary object instead of the float type.

The dict.get() method returns the value of the given key. The get() method will not throw KeyError if the key is not present; instead, we get the None value or the default value that we pass in the get() method.

# Method returns dict def fetch_data(): output = {"Name": "NordVPN", "Price": "22.22"} return output data = fetch_data() # Get the Price print(data.get("Price"))

Output

22.22 Solution 2 – Check if the object is of type dictionary using type

Another way is to check if the object is of type dictionary; we can do that using the type() method. This way, we can check if the object is of the correct data type before calling the get() method.

# Method returns dict def fetch_data(): output = {"Name": "NordVPN", "Price": "22.22"} return output data = fetch_data() # Get the Price if (type(data) == dict): print(data.get("Price")) else: print("The object is not dictionary and it is of type ", type(data))

Output

22.22 Solution 3 – Check if the object has get attribute using hasattr

Before calling the get() method, we can also check if the object has a certain attribute. Even if we call an external API which returns different data, using the hasattr() method, we can check if the object has an attribute with the given name.

# Method returns dict def fetch_data(): output = {"Name": "NordVPN", "Price": "22.22"} return output data = fetch_data() # Get the Price if (hasattr(data, 'get')): print(data.get("Price")) else: print("The object does not have get attribute")

Output

22.22 Conclusion

The AttributeError: ‘float’ object has no attribute ‘get’ occurs when you try to call the get() method on the floatdata type. The error also occurs if the calling method returns an float instead of a dictionary object.

We can resolve the error by calling the get() method on the dictionary object instead of an float. We can check if the object is of type dictionary using the type() method, and also, we can check if the object has a valid get attribute using hasattr() before performing the get operation.

Categories: FLOSS Project Planets

ItsMyCode: [Solved] AttributeError: &#8216;list&#8217; object has no attribute &#8216;get&#8217;

Planet Python - Wed, 2022-06-22 15:56

The AttributeError: ‘list’ object has no attribute ‘get’ mainly occurs when you try to call the get() method on the list data type. The attribute get() method is present in the dictionary and must be called on the dictionary data type.

In this tutorial, we will look at what exactly is AttributeError: ‘list’ object has no attribute ‘get’ and how to resolve this error with examples.

What is AttributeError: ‘list’ object has no attribute ‘get’?

If we call the get() method on the list data type, Python will raise an AttributeError: ‘list’ object has no attribute ‘get’. The error can also happen if you have a method which returns an list instead of a dictionary.

Let us take a simple example to reproduce this error.

# Method return list of dict def fetch_data(): cars = [ {'name': 'Audi', 'price': 45000}, {'name': 'Ferrari', 'price': 450000}, {'name': 'BMW', 'price': 55000}, ] return cars data = fetch_data() print(data.get("name"))

Output

AttributeError: 'list' object has no attribute 'get'

In the above example, we have a method fetch_data() which returns an list of dictionary object instead of a dictionary.

Since we call the get() method directly on the list type, we get AttributeError.

We can also check if the variable type using the type() method, and using the dir() method, we can also print the list of all the attributes of a given object.

# Method return list of dict def fetch_data(): cars = [ {'name': 'Audi', 'price': 45000}, {'name': 'Ferrari', 'price': 450000}, {'name': 'BMW', 'price': 55000}, ] return cars data = fetch_data() print("The type of the object is ", type(data)) print("List of valid attributes in this object is ", dir(data))

Output

The type of the object is <class 'list'> List of valid attributes in this object is ['__add__', '__class__', '__class_getitem__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort'] How to fix AttributeError: ‘list’ object has no attribute ‘get’?

Let us see how we can resolve the error.

Solution 1 – Call the get() method on valid dictionary

We can resolve the error by calling the get() method on the valid dictionary object instead of the list type.

Since the data has a valid dictionary object inside the list, we can loop through the list and use the get() method on the dictionary elements.

The dict.get() method returns the value of the given key. The get() method will not throw KeyError if the key is not present; instead, we get the None value or the default value that we pass in the get() method.

# Method return list of dict def fetch_data(): cars = [ {'name': 'Audi', 'price': 45000}, {'name': 'Ferrari', 'price': 450000}, {'name': 'BMW', 'price': 55000}, ] return cars data = fetch_data() for item in data: print(item.get("name"))

Output

Audi Ferrari BMW

We can also use the generator expression, filter function to get specific dictionary element, or directly use the index of the list. Let us look at each of these with examples.

# Method return list instead of dict def fetch_data(): cars = [ {'name': 'Audi', 'price': 45000}, {'name': 'Ferrari', 'price': 450000}, {'name': 'BMW', 'price': 55000}, ] return cars data = fetch_data() # Generator expression to get specific element car_obj = next( (x for x in data if x['name'] == 'BMW'), {} ) print(car_obj) print("Car Name is ", car_obj.get("name")) print("Car Price is ", car_obj.get("price")) # Directly access the dictionary using the index of list print("The car name in index 0 is ", data[0].get("name"))

Output

{'name': 'BMW', 'price': 55000} Car Name is BMW Car Price is 55000 The car name in index 0 is Audi Solution 2 – Check if the object is of type dictionary using type

Another way is to check if the object is of type dictionary; we can do that using the type() method. This way, we can check if the object is of the correct data type before calling the get() method.

# Method return list of dict def fetch_data(): cars = [ {'name': 'Audi', 'price': 45000}, {'name': 'Ferrari', 'price': 450000}, {'name': 'BMW', 'price': 55000}, ] return cars # assigns the list of dict data = fetch_data() if (type(data) == dict): print(data.get("name")) else: print("The object is not dictionary and it is of type ", type(data)) # assign the index 0 dict my_car =data[0] if (type(my_car) == dict): print(my_car.get("name")) else: print("The object is not dictionary and it is of type ", type(my_car))

Output

The object is not dictionary and it is of type <class 'list'> Audi Solution 3 – Check if the object has get attribute using hasattr

Before calling the get() method, we can also check if the object has a certain attribute. Even if we call an external API which returns different data, using the hasattr() method, we can check if the object has an attribute with the given name.

# Method return list of dict def fetch_data(): cars = [ {'name': 'Audi', 'price': 45000}, {'name': 'Ferrari', 'price': 450000}, {'name': 'BMW', 'price': 55000}, ] return cars # assigns the list of dict data = fetch_data() if (hasattr(data, 'get')): print(data.get("name")) else: print("The object does not have get attribute") # assign the index 0 dict my_car = data[0] if (hasattr(my_car, 'get')): print(my_car.get("name")) else: print("The object does not have get attribute")

Output

The object does not have get attribute Audi Conclusion

The AttributeError: ‘list’ object has no attribute ‘get’ occurs when you try to call the get() method directly on the list data type. The error also occurs if the calling method returns an list instead of a dictionary object.

We can resolve the error by calling the get() method on the dictionary object by iterating the list instead of directly calling the get() method on an list. We can check if the object is of type dictionary using the type() method, and also, we can check if the object has a valid get attribute using hasattr() before performing the get operation.

Categories: FLOSS Project Planets

MiTubo comes to macOS

Planet KDE - Wed, 2022-06-22 15:44

I just released MiTubo 1.2. New in this version:

  • As suggested by alphas12 in the comments, I added the author name in the YouTube search results.
  • In the same results list, there's now a clickable link to the channel, which makes it easier to subscribe to it.
  • Improve layout of some pages on narrow displays (though there's still much to be done!).
  • Skip invoking youtube-dl if the video information is already encoded in the page HEAD meta properties.
  • Remember the preferred playback resolution; this can be helpful on low bandwith connections.
  • First macOS release!

While bringing in the macOS version, I updated the QScreenSaver library to support inhibiting the screensaver on macOS too.

I also tested the AppImage on openSUSE, and it seems to work fine there too. So, fewer and fewer people have valid excuses not to try out MiTubo!

Categories: FLOSS Project Planets

ItsMyCode: [Solved] AttributeError: &#8216;int&#8217; object has no attribute &#8216;get&#8217;

Planet Python - Wed, 2022-06-22 15:16

The AttributeError: ‘int’ object has no attribute ‘get’ mainly occurs when you try to call the get() method on the integer type. The attribute get() method is present in the dictionary and must be called on the dictionary data type.

In this tutorial, we will look at what exactly is AttributeError: ‘int’ object has no attribute ‘get’ and how to resolve this error with examples.

What is AttributeError: ‘int’ object has no attribute ‘get’?

If we call the get() method on the integer data type, Python will raise an AttributeError: ‘int’ object has no attribute ‘get’. The error can also happen if you have a method which returns an integer instead of a dictionary.

Let us take a simple example to reproduce this error.

# Method return integer instead of dict def fetch_data(): output = 100 return output data = fetch_data() print(data.get("name"))

Output

AttributeError: 'int' object has no attribute 'get'

In the above example, we have a method fetch_data() which returns an integer instead of a dictionary.

Since we call the get() method on the integer type, we get AttributeError.

We can also check if the variable type using the type() method, and using the dir() method, we can also print the list of all the attributes of a given object.

# Method return integer instead of dict def fetch_data(): output = 100 return output data = fetch_data() print("The type of the object is ", type(data)) print("List of valid attributes in this object is ", dir(data))

Output

The type of the object is <class 'int'> List of valid attributes in this object is ['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'as_integer_ratio', 'bit_count', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes'] How to fix AttributeError: ‘int’ object has no attribute ‘get’?

Let us see how we can resolve the error.

Solution 1 – Call the get() method on valid dictionary

We can resolve the error by calling the get() method on the valid dictionary object instead of the integer type.

The dict.get() method returns the value of the given key. The get() method will not throw KeyError if the key is not present; instead, we get the None value or the default value that we pass in the get() method.

# Method returns dict def fetch_data(): output = {"Name": "Audi", "Release_Date": "2022", "Price": "$45000"} return output data = fetch_data() # Get the price of the car print(data.get("Price"))

Output

$45000 Solution 2 – Check if the object is of type dictionary using type

Another way is to check if the object is of type dictionary; we can do that using the type() method. This way, we can check if the object is of the correct data type before calling the get() method.

# Method returns dict def fetch_data(): output = {"Name": "Audi", "Release_Date": "2022", "Price": "$45000"} return output data = fetch_data() # Check if the object is dict if (type(data) == dict): print(data.get("Price"))

Output

$45000 Solution 3 – Check if the object has get attribute using hasattr

Before calling the get() method, we can also check if the object has a certain attribute. Even if we call an external API which returns different data, using the hasattr() method, we can check if the object has an attribute with the given name.

# Method returns dict def fetch_data(): output = {"Name": "Audi", "Release_Date": "2022", "Price": "$45000"} return output data = fetch_data() # Check if the object has get attribute if (hasattr(data, 'get')): print(data.get("Price"))

Output

$45000 Conclusion

The AttributeError: ‘int’ object has no attribute ‘get’ occurs when you try to call the get() method on the integer type. The error also occurs if the calling method returns an integer instead of a dictionary object.

We can resolve the error by calling the get() method on the dictionary object instead of an integer. We can check if the object is of type dictionary using the type() method, and also, we can check if the object has a valid get attribute using hasattr() before performing the get operation.

Categories: FLOSS Project Planets

PyCharm: PyCharm 2022.1.3 Is Out!

Planet Python - Wed, 2022-06-22 15:13

We just released PyCharm 2022.1.3, which provides fixes for the important regressions that appeared in 2022.1 and 2022.1.1.

Please note: If you already have PyCharm 2022.1.2 installed, you will need to update to PyCharm 2022.1.3 manually via the Toolbox App or the website.

Download PyCharm 2022.1.3!

Here’s what we’ve done:

  • Fixed a regression with the debug console that was truncating outputs [PY-53983].
  • Fixed a regression causing .pth files to be ignored inside venv site-packages [PY-54321].
  • Cmd+Click / Ctrl+Click in the Git Log panel has been fixed and now works as expected [IDEA-292405].
  • The New Project button on the Welcome screen is once again working as intended [IDEA-276553].
  • Fixed the issue causing a misleading error message when using $var in the calc() function in SCSS files [WEB-54056].
  • Fixed the issue causing an Unexpected term error when using a variable in a min() and max() arguments list [WEB-52057].

For the full list of bug fixes, please take a look at the release notes. If you notice any bugs, please submit them to our issue tracker.

The PyCharm team

Categories: FLOSS Project Planets

Python Morsels: Appreciating Python's match-case by parsing Python code

Planet Python - Wed, 2022-06-22 14:16

Python's match-case blocks are complex structural pattern matching tools that are often more hassle than they're worth. But they're great for parsing abstract syntax trees.

Table of contents

  1. Why remove dataclasses?
  2. Oh, that's what that tool is for?
  3. Using "or patterns" to match multiple sub-patterns
  4. Conditional patterns with guard clauses
  5. Structural pattern matching visually describes the structure of objects
  6. When writing parsers and matchers, consider match-case

Why remove dataclasses?

First let's briefly talk about why I made this tool.

Why would anyone want to convert a dataclass into "not a dataclass"?

There are trade offs with using dataclasses: performance concerns (which don't usually matter) and edge cases where things get weird (__slots__ and slots=True are both finicky). But my reason for creating this dataclass to regular class converter was to help me better teach dataclasses. Seeing the equivalent code for a dataclass helps us appreciate what dataclasses do for us.

Okay let's dive into match-case.

Oh, that's what that tool is for?

I knew the adventure I …

Read the full article: https://www.pythonmorsels.com/match-case-parsing-python/
Categories: FLOSS Project Planets

Lullabot: Paper Prototyping for Websites and Digital Products

Planet Drupal - Wed, 2022-06-22 12:23

Have you ever spent a lot of time on something for your project, only to throw it away? Often someone else interacts with your work and uncovers something important. Perhaps the issue came from a stakeholder, real users, or the implementation team, and their input is important. But now, you have to go back to the drawing board. We can relate.

Categories: FLOSS Project Planets

Peoples BLOG: Quick reference of Code Reviews for Drupal Application

Planet Drupal - Wed, 2022-06-22 12:15
In this article we are going to see how your Drupal team can do code reviews and available tools or libraries which help people in the team to do the code reviews seamlessly. It’s pretty important to follow a few guidelines as well, so that all people or developers in the team are on the same page. Firstly, for the code reviews to be at their best, the committed code should be more organis
Categories: FLOSS Project Planets

LakeDrops Drupal Consulting, Development and Hosting: ECA rules engine for Drupal: RC1 released

Planet Drupal - Wed, 2022-06-22 11:25
ECA rules engine for Drupal: RC1 released Jürgen Haas Wed, 06/22/2022 - 17:25

A huge milestone for the ECA team has finally being reached: it is available for everyone to give it a try. ECA and its main modeller BPMN.iO are considered stable and ready for testing and almost production ready. This is a big achievement after 11 months and around 3.000 hours of architecting, developing and testing the new rules engine for Drupal 9 and 10.

Categories: FLOSS Project Planets

Real Python: Effective Python Testing With Pytest

Planet Python - Wed, 2022-06-22 10:00

Testing your code brings a wide variety of benefits. It increases your confidence that the code behaves as you expect and ensures that changes to your code won’t cause regressions. Writing and maintaining tests is hard work, so you should leverage all the tools at your disposal to make it as painless as possible. pytest is one of the best tools that you can use to boost your testing productivity.

In this tutorial, you’ll learn:

  • What benefits pytest offers
  • How to ensure your tests are stateless
  • How to make repetitious tests more comprehensible
  • How to run subsets of tests by name or custom groups
  • How to create and maintain reusable testing utilities

Free Bonus: 5 Thoughts On Python Mastery, a free course for Python developers that shows you the roadmap and the mindset you’ll need to take your Python skills to the next level.

How to Install pytest

To follow along with some of the examples in this tutorial, you’ll need to install pytest. As most Python packages, pytest is available on PyPI. You can install it in a virtual environment using pip:

PS> python -m venv venv PS> .\venv\Scripts\activate (venv) PS> python -m pip install pytest $ python -m venv venv $ source venv/bin/activate (venv) $ python -m pip install pytest

The pytest command will now be available in your installation environment.

What Makes pytest So Useful?

If you’ve written unit tests for your Python code before, then you may have used Python’s built-in unittest module. unittest provides a solid base on which to build your test suite, but it has a few shortcomings.

A number of third-party testing frameworks attempt to address some of the issues with unittest, and pytest has proven to be one of the most popular. pytest is a feature-rich, plugin-based ecosystem for testing your Python code.

If you haven’t had the pleasure of using pytest yet, then you’re in for a treat! Its philosophy and features will make your testing experience more productive and enjoyable. With pytest, common tasks require less code and advanced tasks can be achieved through a variety of time-saving commands and plugins. It’ll even run your existing tests out of the box, including those written with unittest.

As with most frameworks, some development patterns that make sense when you first start using pytest can start causing pains as your test suite grows. This tutorial will help you understand some of the tools pytest provides to keep your testing efficient and effective even as it scales.

Less Boilerplate

Most functional tests follow the Arrange-Act-Assert model:

  1. Arrange, or set up, the conditions for the test
  2. Act by calling some function or method
  3. Assert that some end condition is true

Testing frameworks typically hook into your test’s assertions so that they can provide information when an assertion fails. unittest, for example, provides a number of helpful assertion utilities out of the box. However, even a small set of tests requires a fair amount of boilerplate code.

Imagine you’d like to write a test suite just to make sure that unittest is working properly in your project. You might want to write one test that always passes and one that always fails:

# test_with_unittest.py from unittest import TestCase class TryTesting(TestCase): def test_always_passes(self): self.assertTrue(True) def test_always_fails(self): self.assertTrue(False)

You can then run those tests from the command line using the discover option of unittest:

(venv) $ python -m unittest discover F. ====================================================================== FAIL: test_always_fails (test_with_unittest.TryTesting) ---------------------------------------------------------------------- Traceback (most recent call last): File "...\effective-python-testing-with-pytest\test_with_unittest.py", line 10, in test_always_fails self.assertTrue(False) AssertionError: False is not true ---------------------------------------------------------------------- Ran 2 tests in 0.006s FAILED (failures=1)

As expected, one test passed and one failed. You’ve proven that unittest is working, but look at what you had to do:

  1. Import the TestCase class from unittest
  2. Create TryTesting, a subclass of TestCase
  3. Write a method in TryTesting for each test
  4. Use one of the self.assert* methods from unittest.TestCase to make assertions

That’s a significant amount of code to write, and because it’s the minimum you need for any test, you’d end up writing the same code over and over. pytest simplifies this workflow by allowing you to use normal functions and Python’s assert keyword directly:

Read the full article at https://realpython.com/pytest-python-testing/ »

[ 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 ]

Categories: FLOSS Project Planets

www @ Savannah: New Article by Richard Stallman

GNU Planet! - Wed, 2022-06-22 09:42

The GNU Education Team has published a new article by Richard Stallman on the threats of Big Tech in the field of education.

Many Governments Encourage Schools to Let Companies Snoop on Students

Human Rights Watch studied 164 software programs and web sites  recommended by various governments for schools to make students use.  It found that 146 of them gave data to advertising and tracking companies.

The researchers were thorough and checked for various snooping methods, including fingerprinting of devices to identify users. The targets of the investigation were not limited to programs and sites specifically “for education;” they included, for instance, Zoom and Microsoft Teams.

I expect that each program collected personal data for its developer. I'm not sure whether the results counted that, but they should. Once the developer company gets personal data, it can provide that data to advertising profilers, as well as to other companies and governments, and it can engage directly in manipulation of students and teachers.

The recommendations Human Rights Watch makes follow the usual approach of regulating the use of data once collected.  This is fundamentally inadequate; personal data, once collected, will surely be misused.

The only approach that makes it possible to end massive surveillance starts with demanding that the software be free. Then users will be able to modify the software to avoid giving real data to companies.

More at gnu/education...

Categories: FLOSS Project Planets

Python for Beginners: Append Dictionary to CSV File in Python

Planet Python - Wed, 2022-06-22 09:00

CSV files are one of the most efficient tools to store structured, tabular data. Sometimes, we might need to append data to the CSV file from a python dictionary. In this article, we will discuss how we can append the values in a dictionary to a CSV file in python. 

Append Dictionary to CSV File Using csv.writer()

You can append a dictionary to CSV file using CSV.writer() method and CSV.writerow() method. For this, we will first open the CSV file in append mode using the open() function. The open() function takes the filename as its first input argument and the literal “a” as its second input argument to denote that the file is opened in the append mode.

After opening the file, we will create a CSV writer object using the CSV.writer() function. The CSV.writer() function takes the file object containing the CSV file as its input argument and returns a writer object. 

After creating the writer object, we will append the dictionary to the CSV file using the writerow() method. The writerow() method, when invoked on a writer object, takes the values in the dictionary as its input argument and appends it to the CSV file.

After execution of the writerow() method, you must close the CSV file using the close() method. Otherwise, the changes won’t be saved in the CSV file. The source code for this approach to append a dictionary to a CSV file is given below.

import csv myFile = open('Demo.csv', 'r+') print("The content of the csv file before appending is:") print(myFile.read()) myDict = {'Roll': 4, 'Name': 'Joel', 'Language': 'Golang'} print("The dictionary is:") print(myDict) writer = csv.writer(myFile) writer.writerow(myDict.values()) myFile.close() myFile = open('Demo.csv', 'r') print("The content of the csv file after appending is:") print(myFile.read())

Output:

The content of the csv file before appending is: Roll,Name,Language 1,Aditya,Python 2,Sam, Java 3, Chris, C++ The dictionary is: {'Roll': 4, 'Name': 'Joel', 'Language': 'Golang'} The content of the csv file after appending is: Roll,Name,Language 1,Aditya,Python 2,Sam, Java 3, Chris, C++ 4,Joel,Golang Append Dictionary to CSV File using csv.DictWriter()

Instead of using the csv.writer() method, we can use the csv.DictWriter() function along with the csv.writerow() method to append a python dictionary to csv file. The approach is almost similar to the approach using the csv.writer() method with the following differences.

  • Instead of the csv.writer() method, we will use the csv.DictWriter() method. The DictWriter() method takes the file object containing the csv file as its input argument and returns a DictWriter object.
  • When the writerow() method is executed on the DictWriter object, it takes a dictionary as the input argument instead of the values in the dictionary.

The python code to append a dictionary to a csv file using csv.DictWriter() is as follows.

import csv myFile = open('Demo.csv', 'r+') print("The content of the csv file before appending is:") print(myFile.read()) myDict = {'Roll': 4, 'Name': 'Joel', 'Language': 'Golang'} print("The dictionary is:") print(myDict) writer = csv.DictWriter(myFile, fieldnames=list(myDict.keys())) writer.writerow(myDict) myFile.close() myFile = open('Demo.csv', 'r') print("The content of the csv file after appending is:") print(myFile.read())

Output:

The content of the csv file before appending is: Roll,Name,Language 1,Aditya,Python 2,Sam, Java 3, Chris, C++ The dictionary is: {'Roll': 4, 'Name': 'Joel', 'Language': 'Golang'} The content of the csv file after appending is: Roll,Name,Language 1,Aditya,Python 2,Sam, Java 3, Chris, C++ 4,Joel,Golang Conclusion

In this article, we have discussed two ways to append a dictionary to csv file in python. In these approaches, the dictionary will be appended irrespective of whether it has same number of items as compared to the columns in the csv file or it has the same keys as compared to the column names in the csv file. Thus it advised to make sure that the dictionary should have the same number of keys as compared to the columns in the csv file. Also You should make sure that the order of columns of the csv file should be same as the order of the keys present in the dictionary. Otherwise, the data appended to the csv file will become inconsistent and will lead to errors. 

I hope you enjoyed reading this article.To know more about dictionaries in python, you can read this article on dictionary comprehension in python. You might also write this article on list comprehension in python.

Stay tuned for more informative articles.

Happy Learning!

The post Append Dictionary to CSV File in Python appeared first on PythonForBeginners.com.

Categories: FLOSS Project Planets

ANNAI Magazine: Migrating Japanese Digital Agency's website to Drupal: ANNAI's talk at Drupalcon Portland 2022

Planet Drupal - Wed, 2022-06-22 08:51

We gave a talk at Drupalcon Portland 2022 about the Unified Government Website project we have been working on, as well as the migration of the Japanese Digital Agency website to a Headless CMS (Drupal + Next.js) as a feasibility study.

The talk consisted of three parts:

  1. Migration of the Digital Agency website to a headless CMS
  2. Research project for the realisation of a unified government website
  3. The future direction of the project

This blog post describes the first part above.

Categories: FLOSS Project Planets

Talk Python to Me: #370: OpenBB: Python's Open-source Investment Platform

Planet Python - Wed, 2022-06-22 04:00
You may have heard of the Bloomberg terminal. It's expensive software that can monitor and analyze real-time financial market data and place trades on the electronic trading platform. But have you heard of OpenBB? It's similar software for real-time and long term analysis for finance and investing. The difference is it's open source and built entirely with Python and gives you access to analyze a massive amount of real-time and historical data using the full Python data science stack. On this episode, we have one of the cofounders, James Maslek here to give us a look inside this cool piece of Python-based software.<br/> <br/> <strong>Links from the show</strong><br/> <br/> <div><b>James Maslek</b>: <a href="https://www.linkedin.com/in/james-maslek/" target="_blank" rel="noopener">linkedin.com</a><br/> <b>OpenBB</b>: <a href="https://www.openbb.co" target="_blank" rel="noopener">openbb.co</a><br/> <b>OpenBB Feature Gallery</b>: <a href="https://openbb.co/products/terminal" target="_blank" rel="noopener">openbb.co</a><br/> <b>$8.5M seed funding announcement</b>: <a href="https://www.openbb.co/blog/gme-didnt-take-me-to-the-moon-but-gamestonk-terminal-did" target="_blank" rel="noopener">openbb.co/blog</a><br/> <b>How to get rich talk by Naval (less money-focused than the title implies)</b>: <a href="https://www.youtube.com/watch?v=1-TZqOsVCNM" target="_blank" rel="noopener">youtube.com</a><br/> <b>Watch this episode on YouTube</b>: <a href="https://www.youtube.com/watch?v=BbqvRqMbVFU" target="_blank" rel="noopener">youtube.com</a><br/> <b>Episode transcripts</b>: <a href="https://talkpython.fm/episodes/transcript/370/openbb-pythons-open-source-investment-platform" target="_blank" rel="noopener">talkpython.fm</a><br/> <br/> <b>--- Stay in touch with us ---</b><br/> <b>Subscribe to us on YouTube</b>: <a href="https://talkpython.fm/youtube" target="_blank" rel="noopener">youtube.com</a><br/> <b>Follow Talk Python on Twitter</b>: <a href="https://twitter.com/talkpython" target="_blank" rel="noopener">@talkpython</a><br/> <b>Follow Michael on Twitter</b>: <a href="https://twitter.com/mkennedy" target="_blank" rel="noopener">@mkennedy</a><br/></div><br/> <strong>Sponsors</strong><br/> <a href='https://talkpython.fm/sentry'>Sentry Error Monitoring, Code TALKPYTHON</a><br> <a href='https://talkpython.fm/python-at-scale'>Python at Scale</a><br> <a href='https://talkpython.fm/assemblyai'>AssemblyAI</a><br> <a href='https://talkpython.fm/training'>Talk Python Training</a>
Categories: FLOSS Project Planets

Python Anywhere: Anaconda Acquisition FAQs

Planet Python - Tue, 2022-06-21 20:00
In June 2022, Anaconda announced its acquisition of PythonAnywhere. This acquisition expands Python team collaboration in the cloud and adds capabilities designed to unite teams and create access to more robust cloud resources. We’ve compiled the following list of frequently asked questions to aid users in navigating the transition. – Will this affect my PythonAnywhere account? For now, it won’t! There are no plans to change PythonAnywhere user accounts, and you can continue to use yours as usual without interruption.
Categories: FLOSS Project Planets

FSF Events: Free Software Directory on IRC: Friday, June 24 starting at 12:00 p.m. EDT (14:00 UTC)

GNU Planet! - Tue, 2022-06-21 16:34
Join the FSF and friends Friday, June 24, from 12:00 p.m. to 3 p.m. EDT (14:00 to 17:00 UTC) to help improve the Free Software Directory.
Categories: FLOSS Project Planets

PyCoder’s Weekly: Issue #530 (June 21, 2022)

Planet Python - Tue, 2022-06-21 15:30

#530 – JUNE 21, 2022
View in Browser »

Objects, Functions, Generators, and Coroutines

Although different concepts, objects, functions, generators, and coroutines can be used almost interchangeably because of Python’s dynamic nature. Learn more about how these mechanisms are related and how to switch between them.
DUSTY PHILLIPS

Combining Data in pandas With concat() and merge()

In this video course, you’ll learn two techniques for combining data in pandas: merge() and concat(). Combining Series and DataFrame objects in pandas is a powerful way to gain new insights into your data.
REAL PYTHON course

ButterCMS Melts Into Your Python app. Try the #1 Headless CMS for Python and Django

ButterCMS is your content backend. Enable your marketing team to update website + app content without bothering you. Try the #1 rated Headless CMS for Python today. Free for 30 days →
BUTTERCMS sponsor

Getting Lazy With Python Imports and PEP 690

Talk Python interviews all three authors involved in PEP 690, a proposal to add the ability to delay library importation until time of use.
KENNEDY, MEYER, BRAVO, & WARSAW podcast

Django CMS Fellowship Program: Apply Now

DJANGO-CMS.ORG

DjangoCon Europe Call for Hosting Proposals for 2023

DJANGO SOFTWARE FOUNDATION

PyOhio Talks Announced; Free Registration; Streams July 30

PYOHIO.ORG

Discussions Most Common Issue You Have Coding With Python?

MATT HARRISON

What’s a Powerful Python Feature That Not Many People Use?

REDDIT

Python Jobs Senior Python Software Engineer (San Francisco, CA, USA)

MyOme

Senior Full-Stack Web Developer (Anywhere)

MonetizeMore

Backend Software Developer (Draper, UT, USA)

Canopy

Gameful Learning Developer (Ann Arbor, MI, USA)

University of Michigan

Python Technical Architect (USA)

Blenderbox

Software Engineer (Los Angeles or Dallas) (Los Angeles, CA, USA)

Causeway Capital Management LLC

DevOps Engineer (Ann Arbor, MI, USA)

University of Michigan

Academic Innovation Developer (Ann Arbor, MI, USA)

University of Michigan

Software Development Lead (Ann Arbor, MI, USA)

University of Michigan

Principal Python Engineer (100% Remote) (San Francisco, CA, USA)

Nira

More Python Jobs >>>

Articles & Tutorials Build Your Python Project Documentation With MkDocs

In this tutorial, you’ll learn how to build professional documentation for a Python package using MkDocs and mkdocstrings. These tools allow you to generate nice-looking and modern documentation from Markdown files and, more importantly, from your code’s docstrings.
REAL PYTHON

Getting the Stack Trace of a Running Python Program

“I recently wanted to examine a multi-threaded Python program, which took a long time to complete, appeared to be stuck, and even crashed occasionally. I was hoping to get the stack trace.” Peter shares the code that solved his problem and how to test with it.
PETER KOGAN

Connect, Integrate, & Automate Your Data—From Python, or Any Other Application or Tool

CData makes it easier to unlock the value of data — simplifying connectivity between applications and data sources. Our SQL-based connectors streamline data access making it easy to access real-time data from on-premise and cloud databases, SaaS, APIs, NoSQL and more. Visit cdata.com to learn more →
CDATA SOFTWARE sponsor

Getting Started in Python Cybersecurity and Forensics

Are you interested in a career in security using Python? Would you like to stay ahead of potential vulnerabilities in your Python applications? This week on the show, James Pleger talks about Python information security, incident response, and forensics.
REAL PYTHON podcast

Tools To Visualize Your Data and System State

This overview covers a variety of tools for visualizing data formats such as JSON, regexes, SQL, and Git history. If that’s not enough, it then goes on to describe tools to better understand your Docker and Kubernetes configurations.
MARTIN HEINZ

Python Logging: Do’s and Don’ts

Python’s logging library can be a daunting to new users, with lots of options and configuration. Learn more about some key things you should and shouldn’t do when using logger.
PALKEO

Utilising Caching in Your Django Applications

Minimizing the number of database calls can have significant performance impacts. Learn about select_related and prefetch_related and how they can improve your Django code.
MARK WALKER

Illustrating the Duality of Closures and Objects

In functional programming languages, closures are used for similar purposes to classes in object oriented languages. Python supports both, learn more about how they compare.
JONATHAN E. MAGEN

Get Started With This PyCharm Debugging Tutorial From Rookout

Need to hit the ground running with a new app in a cool IDE? This tutorial will cover an example of debugging Python in PyCharm, the pros and cons of “remote debugging,” and where a tool like Rookout fills in the gaps on syncing with source code.
ROOKOUT sponsor

Create Dashboards From Jupyter Notebooks

This article shows you how to transform a Jupyter Notebook with stock information into a web-based dashboard using the Mercury framework.
ALEKSANDRA PŁOŃSKA

A Beginner’s Guide to CI/CD and Automation on GitHub

“CI/CD and workflow automation are native capabilities on GitHub platform. Here’s how to start using them and speed up your workflows.”
THE GITHUB BLOG

Projects & Code onto_merger: Deduplicate Knowledge Graph Nodes

GITHUB.COM/ASTRAZENECA • Shared by Benedek Rozemberczki

deny: Python Authorization Library

GITHUB.COM/HOLINNN

Task Queues: List of Task Queues and Message Brokers

TASKQUEUES.COM

pedalboard: Audio Effects Library

GITHUB.COM/SPOTIFY

euchre: Interactive, Text-Based Euchre Game in Python

GITHUB.COM/DAVID-HOLROYD

Events GeoPython 2022

June 20 to June 23, 2022
GEOPYTHON.NET

Weekly Real Python Office Hours Q&A (Virtual)

June 22, 2022
REALPYTHON.COM

PyKla Monthly Meetup

June 22, 2022
MEETUP.COM

PyStaDa

June 22, 2022
PYSTADA.GITHUB.IO

PythOnRio Meetup

June 25, 2022
PYTHON.ORG.BR

PyCon Israel 2022

June 28 to June 30, 2022
PYCON.ORG.IL

(Hybrid) a Deep Dive Into Containerized Model Serving With FastAPI

June 28, 2022
MEETUP.COM

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

[ 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 ]

Categories: FLOSS Project Planets

Pages