Python Error – Java2Blog https://java2blog.com A blog on Java, Python and C++ programming languages Sat, 25 Nov 2023 12:04:37 +0000 en-US hourly 1 https://wordpress.org/?v=6.2.9 https://java2blog.com/wp-content/webpc-passthru.php?src=https://java2blog.com/wp-content/uploads/2022/09/cropped-ICON_LOGO_TRANSPARENT-32x32.png&nocache=1 Python Error – Java2Blog https://java2blog.com 32 32 How to fix TypeError: A Bytes-Like object Is Required, Not ‘str’? https://java2blog.com/typeerror-a-bytes-like-object-is-required-not-str/?utm_source=rss&utm_medium=rss&utm_campaign=typeerror-a-bytes-like-object-is-required-not-str https://java2blog.com/typeerror-a-bytes-like-object-is-required-not-str/#respond Tue, 09 Feb 2021 18:46:14 +0000 https://java2blog.com/?p=12703 ◈ Problem Formulation

Suppose you have the following file given below and you want to check the price for a certain product.

Now, you want to check the price for Samsung Galaxy S21 using the following piece of code:

with open('file.txt', 'rb') as f:
    lines = [x.strip() for x in f.readlines()]

for line in lines:
    tmp = line.strip()
    split_line = tmp.split('-')
    price = (str(split_line[1]).replace(' ', ''))
    if split_line[0] == 'Samsung Galaxy S21 ':
        print("Price = ", split_line[1])

But when you execute your code, you receive the following output:
Output:

Traceback (most recent call last):
  File "D:/PycharmProjects/pythonProject1/TypeError.py", line 6, in <module>
    split_line = tmp.split('-')
TypeError: a bytes-like object is required, not 'str'

So, this brings us to the question – What is a TypeError? What causes such errors in our program?
Hence, without further delay let us understand the reason behind the occurrence of TypeError and the ways to fix such errors.

◈ What Is TypeError in Python?

A TypeError is generally raised when a certain operation is applied to an object of an incorrect type.
Example:

print('Java'+2+'Blog')

Output:

TypeError: can only concatenate str (not "int") to str

In the above, we tried to add a string object and an integer object using the + operator. This is not allowed and hence we encountered a TypeError.

There can be numerous reasons that lead to the occurrence of TypeError. Some of these reasons are:

  • Trying to perform an unsupported operation between two types of objects.
  • Trying to call a non-callable caller.
  • Trying to iterate over a non-iterative identifier.

Now that we have a clear idea about TypeErrors, let us find out the reason behind the occurrence of TypeError error in our code.

☞ How To Fix TypeError: A Bytes-Like object Is Required, Not ‘str’

We opened the file as: with open('file_sample.txt', 'rb'). Here rb denotes binary mode which means that all the data being read from the file is returned as bytes. Hence, when you look at line 6, you will find that we are trying to split a byte object using a string. This operation is not allowed and leads to to a TypeError.

So, how do we fix this error in our program? 🤔 Let’s dive into the methods to solve our problem!

✨Method 1: Convert To Bytes Object

The easiest solution to our problem is to ensure that the object types match by converting the delimiter string within the split() function to a byte object. You can achieve this by using the prefix b before the delimiter string within the split() function. This allows you to operate upon a byte object within the split() function, thereby avoiding the TypeError.

Solution:

with open('file.txt', 'rb') as f:
    lines = [x.strip() for x in f.readlines()]

for line in lines:
    tmp = line.strip()
    split_line = tmp.split(b'-')
    if split_line[0] == b'Samsung Galaxy S21 ':
        print("Price = ", split_line[1])

Output:

Price =  b' Rs.1,05,999.00 ;'

✨ Method 2: Using decode()

In our code, we are trying to read the file in binary mode and then creating a list of bytes. In the for loop, we are comparing the string to bytes and that is exactly where the code is failing. So to overcome this, you can decode the bytes while adding them to the list using the decode() function.

❖ The decode() method allows you to convert from one encoding scheme, in which the argument string is encoded to another desired encoding scheme. 

Let us have a look at the following code to understand how we can fix the TypeError in our code.

with open('file.txt', 'rb') as f:
    lines = [x.decode('utf8').strip() for x in f.readlines()]

for line in lines:
    tmp = line.strip()
    split_line = tmp.split('-')
    if split_line[0] == 'Samsung Galaxy S21 ':
        print("Price = ", split_line[1])

Output:

Price =   Rs.1,05,999.00 ;

✨ Method 3: Using Encode()

❖ The encode() method in Python is used to encode the string, using the specified encoding.

Therefore, you can encode the delimiter string within the split() function using .encode() and then proceed with the next steps in your program as shown below.

with open('file.txt', 'rb') as f:
    lines = [x.strip() for x in f.readlines()]

for line in lines:
    tmp = line.strip()
    split_line = tmp.split('-'.encode())
    if 'Samsung Galaxy S21 ' in str(split_line[0]):
        print("Price = ", split_line[1])

Output:

Price =  b' Rs.1,05,999.00 ;'

✨ Method 4: Open The File in Text Mode

Another work-around to our problem is to open the file in text mode. You can achieve this by using rt instead of rb inside the open() function.

Solution:

with open('file.txt', 'rt') as f:
    lines = [x.strip() for x in f.readlines()]

for line in lines:
    tmp = line.strip()
    split_line = tmp.split('-')
    if 'Samsung Galaxy S21 ' in str(split_line[0]):
        print("Price = ", split_line[1])

Output:

Price =   Rs.1,05,999.00 ;

Conclusion

In this article we learned:

  • What is TypeError?
  • Reasons behind TypeError?
  • How To Fix TypeError: A Bytes-Like object Is Required, Not ‘str’?
    • Method 1: By Converting Types to Byte type object.
    • Method 2: Using encode() function.
    • Method 3: Using decode() function.
    • Method 4: Opening the file in text mode.

With that, we come to the end of this article and I hope you enjoyed learning! Please subscribe and stay tuned for more interesting articles and discussions in the future. Happy Learning! 📚

]]>
https://java2blog.com/typeerror-a-bytes-like-object-is-required-not-str/feed/ 0
NameError: Name requests Is Not Defined https://java2blog.com/nameerror-name-requests-is-not-defined/?utm_source=rss&utm_medium=rss&utm_campaign=nameerror-name-requests-is-not-defined https://java2blog.com/nameerror-name-requests-is-not-defined/#respond Sat, 15 Apr 2023 06:15:23 +0000 https://java2blog.com/?p=23420 Python has a name error when you try to use a variable or function that is not defined currently. It means that Python has no idea where to locate the requests module or library you are trying to use in your code when you receive the nameError: name 'requests' is not defined error.

There are several reasons why you might encounter the NameError: name 'requests' is not defined error in Python. Among the most common causes are:

  1. The request Module is not Installed: If you are trying to use the requests module in your code, but it is not installed
  2. Missing import statement: If you are trying to use the requests module in your code, but you have not imported it.
  3. Incorrect spelling: If you have misspelt the name of the requests module in your code.
  4. Missing installation: If you have not installed the requests module on your system but trying to import it for further use.

Let’s reproduce the error first which will lead us to possible solutions.

Reproducing NameError in Python

Use requests module in Python 3.x to reproduce the NameError in Python.

import requests
url = "https://www.w3schools.com/html/html_examples.asp"
response = request.get(url)
print(response.text)

NameError                                 Traceback (most recent call last)
Cell In [8], line 3
      1 import requests
      2 url = "https://www.w3schools.com/html/html_examples.asp"
----> 3 response = request.get(url)
      4 print(response.text)
NameError: name 'request' is not defined

The above code starts by importing the requests module, a Python library for sending HTTP requests. It then sets a variable named url to a website URL string. The code then sends an HTTP GET request to the URL using the request.get() method and stores the response object in a variable named response.

Finally, the code prints the content of the response object as text using the response.text attribute. This code uses the requests library to make an HTTP GET request. However, when we try to execute this code, it displays a NameError: name 'request' is not defined' error on the console.

Possible Solutions to Fix NameError in Python

If you encounter the NameError: name 'requests' is not defined error in your Python code, here are some steps you can take to fix it:

Solution 1: pip Module Installation

Ensure you have installed the requests module on your system using the pip package manager.

Install pip using Python 3

We can install the requests module using the following command.

<pre code = Python Title = ‘Install requests Module’>
pip install requests

Check Your import Statement

  1. Ensure you have imported the requests module in your code using the import statement as import requests. See the following example.

<pre code = Python Title = ‘Import requests Module’>
import requests
response = requests.get(‘https://www.w3schools.com/html/html_examples.asp‘)
print(response.text)

In this code, the requests module is imported, and the get() method is used to make an HTTP GETrequest to the specified URL. The response.text is an attribute in the Response object in the requests library that returns the HTTP response body as a string.

  1. Ensure you have spelt the name of the requests module correctly everywhere in your code. The module name is requests, with no capital letters or spaces.

Solution 2: requests Module is Out of Nested Scope

The error message stating requests module is out of nested scope typically occurs when you try to use the requests module inside a nested function or class. See the following example.

def my_function():
import requests
def nested_function():
     response = requests.get('https://www.w3schools.com/html/html_examples.asp')
nested_function()

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_15364/3784162057.py in <module>
      3 def nested_function():
      4     response = requests.get('https://www.w3schools.com/html/html_examples.asp')
----> 5 nested_function()
~\AppData\Local\Temp/ipykernel_15364/3784162057.py in nested_function()
      2     import requests
      3 def nested_function():
----> 4     response = requests.get('https://www.w3schools.com/html/html_examples.asp')
      5 nested_function()
NameError: name 'requests' is not defined

In this example, the requests module is imported inside the my_function function, and then used inside a nested function nested_function().

When the nested function is called, Python will look for the requests module in the local namespace of the nested_function() first, and since it’s not found there, it will look in the local namespace of the my_function(). Since the requests module is not defined in the my_function() namespace, Python will raise a NameError with the message "requests Module is Out of Nested Scope".

Solution 3: requests Module Imported into the Global

Import requests module in global namespace in Python.

import requests
def my_function():
    def nested_function(requests_module):
        response = requests_module.get('https://www.w3schools.com/html/html_examples.asp')
        print(response.text)
    nested_function(requests)
my_function()

In this example, the requests module is imported in the global namespace and then passed as an argument to the nested_function() function. When the function is called, the requests module is passed as an argument to the function and used as requests_module inside the function.

Considering the above discussion, the NameError: name 'requests' is not defined error occurs when the Python interpreter cannot find the requests library in the current environment. This error can be easily fixed by ensuring the requests module is imported, spelt, and installed correctly.

Following best practices, such as importing modules at the beginning of your code, using descriptive variable names, and keeping dependencies up-to-date, can help you avoid this error in the future.

That’s all about NameError: Name requests Is Not Defined.

]]>
https://java2blog.com/nameerror-name-requests-is-not-defined/feed/ 0
NameError: Name xrange Is Not Defined in Python https://java2blog.com/nameerror-name-xrange-is-not-defined-python/?utm_source=rss&utm_medium=rss&utm_campaign=nameerror-name-xrange-is-not-defined-python https://java2blog.com/nameerror-name-xrange-is-not-defined-python/#respond Fri, 14 Apr 2023 10:18:37 +0000 https://java2blog.com/?p=23425 This NameError: Name 'xrange' Is Not Defined in Python is one of the errors which can occur while using Python. Our objective is to identify the underlying cause of the error and then provide ways to resolve it.

Using xrange() Method to Reproduce NameError

Use the xrange() method to reproduce NameError in Python 3.x.

for x in xrange(1, 5):
    print(x)

Traceback (most recent call last):
  File "/home/jdoodle.py", line 1, in <module>
    for x in xrange(1, 5):
NameError: name 'xrange' is not defined

When someone tries to use the xrange() method in the Python 3.x version, the NameError: Name 'xrange' Is Not Defined error occurs because the interpreter does not recognize it. This xrange() function is unavailable in Python 3.x or later. It was available in Python 2.x, but in later versions, it is updated as the range() method, which works similarly to the xrange() method but has a different keyword.

What could happen if we used the above code in Python 2.x? As we know that the xrange() is a built-in method in Python 2.x version to provide a range of the integers; so, the above code could produce integers from 1 to 4, the ending number in xrange() method is excluded from the output.

The point is resolving the above-mentioned error in Python 3.x if we have to face it. So let’s learn it in the following section.

Possible Solutions to Resolve NameError: Name xrange Is Not Defined in Python

We can use one of the following solutions to resolve the NameError: Name 'xrange' Is Not Defined error.

Use range() Method

If you use Python 3.x or later versions, replace the xrange() method with range() in your code to resolve this error.

for x in range(1, 5):
    print(x)

1
2
3
4

In the above code snippet, the range() method generates integers from 1 up to 5.

The output of range() is similar to the xrange() method output.

Let’s consider a scenario in which we used the range() function to generate a range of integers having a specific difference. In that case, the range() will take three parameters: start, stop, and step, briefly explained below.

Parameters Meaning
start (inclusive) It represents the start of the range we want to generate. By default, it is 0.
stop (exclusive) It represents the end of the range; it will not include in the range.
step It represents the step size or difference between the integers by default step is 1.

See the following example to learn the use of the above-mentioned parameters:

for x in range(0, 10, 2):
    print(x)

0
2
4
6
8

In this example, the range method generated integers from 0 up to 10 with the difference of 2 steps. If you are using Python 2.x or an older version, you can use the xrange() method in the same way, to generate numbers with specific step differences.

Use xrange=range

Another solution to fix the error in Python 3.x is to make these two methods equal, as shown below.

xrange = range
for x in range(5):
    print(x)

0
1
2
3
4

We can observe xrange = range is used in the above example to fix the NameError: Name 'xrange' Is Not Defined in Python error. So, if you are getting this error, add xrange = range in your code, and boom! It will be resolved.

Use past.builtins Library

To resolve this NameError: Name 'xrange' Is Not Defined in Python error, import the built-in methods from the previous versions in Python 3.x using the past.builtins library, as shown below.

from past.builtins import xrange
for x in xrange(5):
    print(x)

0
1
2
3
4

In this example, the xrange method is imported from the past.builtins library, which contains all the built-in methods of previous python versions.

That’s all abput how to fix NameError: Name xrange is Not Defined in Python.

]]>
https://java2blog.com/nameerror-name-xrange-is-not-defined-python/feed/ 0
TypeError: ‘dict_values’ Object Is Not Subscriptable https://java2blog.com/typeerror-dict_values-object-is-not-subscriptable/?utm_source=rss&utm_medium=rss&utm_campaign=typeerror-dict_values-object-is-not-subscriptable https://java2blog.com/typeerror-dict_values-object-is-not-subscriptable/#respond Sun, 09 Apr 2023 17:58:01 +0000 https://java2blog.com/?p=23382 Reproducing TypeError: ‘dict_values object is not subscriptable

When you try to access the dict_values object through index, the error will raise stating TypeError: 'dict_values' object is not subscriptable. Here is the example below.

my_dict = {'a': 1, 'b': 2, 'c': 3}
print(my_dict.values()[0])

TypeError                                 Traceback (most recent call last)
<ipython-input-4-eb4c6bca4286> in <module>
      1 my_dict = {'a': 1, 'b': 2, 'c': 3}
----> 2 print(my_dict.values()[0])

TypeError: 'dict_values' object is not subscriptable

Convert dict_values object to list

To resolve TypeError: 'dict_values object is not subscriptable, convert dict_values object to list before accessing it using index.

Let’s take an example that uses the list() function to convert the dict_values object into a list.

my_dict = {'a': 4, 'b': 5, 'c': 6}
values_list = list(my_dict.values())
print(values_list)

[4, 5, 6]

Here, we used the dictionary’s values() method to get a dict_values object containing all the values. Then, we enclosed the dict_values object within the list() method to change its type from dict_values to list, which we stored in the values_list variable.

Finally, we used the print() method to display values_list.

The values of the dictionaries can be accessed through the key or the values() method. In addition, the specific value of the dictionary can be accessed or can retrieve all the values. Use the following methods to access the Dictionary values.

Using Key to Access Specific Value of Dictionary

Use the specified key to retrieve the particular value of the dictionary in Python.

my_dict = {'a': 1, 'b': 2, 'c': 3}
value_b = my_dict['b']
print(value_b)

2

First, we defined the dictionary named my_dict with three key-value pairs 'a': 1, 'b': 2, 'c': 3. Then, we accessed the specific value 2 from the dictionary using its key 'b'. Finally, we used the print() method to print the value of 'b' on the output screen, which is 2.

Using for Loop with .values() Method to Access All Values

Use the for loop with the .values() method to retrieve all values of the dictionary in Python.

my_dict = {'a': 1, 'b': 2, 'c': 3}
for value in my_dict.values():
    print(value)

1
2
3

To access all the values in a dictionary, we can use a loop or convert the dict_values object into a list or a tuple; we used the for loop for the above code, iterated over the dictionary and printed the values against all keys. In this method, the built-in values() method is used to get all values.

To conclude, convert dict_values object to list, use the key to access a specific value or the loop to iterate over all the values using the values() method.

That’s all about how to resolve TypeError: ‘dict_values’ Object Is Not Subscriptable in Python.

]]>
https://java2blog.com/typeerror-dict_values-object-is-not-subscriptable/feed/ 0
[Fixed] NameError Name ‘unicode’ is Not Defined in Python https://java2blog.com/nameerror-name-unicode-is-not-defined-python/?utm_source=rss&utm_medium=rss&utm_campaign=nameerror-name-unicode-is-not-defined-python https://java2blog.com/nameerror-name-unicode-is-not-defined-python/#respond Tue, 27 Dec 2022 05:52:18 +0000 https://java2blog.com/?p=22015 Use str() Method

To resolve the NameError: name 'unicode' is not defined, replace the occurrence of unicode() with str(). This issue occurs because unicode() was renamed to str() in Python 3.

my_string = str('This program resolves \u0061 "NameError" in PythØn!')
print(my_string)

This program resolves a "NameError" in PythØn!

Unicode is a computing industry standard that ensures that text from most of the world’s writing systems is consistently encoded, rendered, and processed.

A Unicode string is composed of Unicode code points written using a backslash followed by a series of four hexadecimal digits.

Its use allows for more excellent compatibility between software programs and operating systems as it is not limited to the ASCII character set, which contains only the Latin alphabet and a few other characters. In addition, it represents letters, glyphs, symbols, and other special characters from any language, providing greater flexibility.

The management of these strings has changed significantly in Python 3. Days are gone of using unicode() for these strings; Python’s str() has taken its place. It is a powerful way that stores and manipulates Unicode characters more efficiently than others.

The str() allows users to create multilingual documents, manipulate the text in different character encodings, and access characters outside the standard ASCII range.

We used the str() class in my_String to read the Unicode code point \0061 as a letter a.

Use sys.version_info with str

To resolve the NameError: name 'unicode' is not defined in Python:

  • Use sys.version_info[0] to check if the version of the Python interpreter is greater than 3. If it is, replace by initializing a unicode variable with an str class.
  • Use unicode() to read the provided Unicode code point as a string.

import sys
if sys.version_info[0] >= 3:
    unicode = str
my_string = unicode('This program resolves \u0061 "NameError" in PythØn!')
print(my_string)

This program resolves a "NameError" in PythØn!

While explaining the code snippet for using the str() class, we covered Unicode, Unicode String, and the str(). In this section, we used the Python sys package.

Python’s sys module provides access to system-specific details, information about the operating system, and operations like retrieving environment variables, executing shell commands, and process management.

It allows the user to access information about the Python interpreter, such as platform, version number, etc.

To provide information about the version of the Python interpreter at runtime, sys provides the version_info attribute.

It is a named tuple with five fields: major, minor, micro, releaselevel, and serial that keeps the interpreter up to date by determining the available features on a given system.

For example, we used this attribute to write code compatible with version 3 of Python with an if condition. If it is, we declare a unicode variable and initialize it with the str class.

We used the unicode to read the Unicode code point \0061 as a letter a and stored it in the my_String.

Use six.text_type

To resolve the NameError: name 'unicode' is not defined in Python, use isinstance(my_string, six.text_type) to check if the string is a Unicode string.

import six
my_string = 'This program resolves \u0061 "NameError" in PythØn!'
if isinstance(my_string, six.text_type):
    print(my_string)

This program resolves a "NameError" in PythØn!

The six library is designed to provide compatibility between different versions of Python by writing code that works across multiple versions with minimal changes.

It allows developers to write code in either version without worrying about whether it will break in another version or not.

Constants from the six library may vary between Python versions. The text_type, which represents textual data, is one of them.

In Python 2, it is unicode, whereas in Python 3, it is str. So, for example, we used the text_type inside an if statement to check if my_String is an instance of six.text_type using the instanceof() function checks whether an object belongs to a given type (class) or not.

That’s all about how to resolve NameError Name ‘unicode’ is not defined in Python.

]]>
https://java2blog.com/nameerror-name-unicode-is-not-defined-python/feed/ 0
TypeError: Object of Type Datetime Is Not Json Serializable in Python https://java2blog.com/typeerror-object-of-type-datetime-is-not-json-serializable-python/?utm_source=rss&utm_medium=rss&utm_campaign=typeerror-object-of-type-datetime-is-not-json-serializable-python https://java2blog.com/typeerror-object-of-type-datetime-is-not-json-serializable-python/#respond Fri, 23 Sep 2022 08:13:12 +0000 https://java2blog.com/?p=20249 In Python, the datetime library allows us to create objects of the datetime class that can store and process date and time values efficiently. We can manipulate these objects according to our needs using the wide range of functionalities provided by this library.

JSON is a type of encoding for data that is used frequently to facilitate the exchange of data over networks. It stands for JavaScript Object Notation. Due to the heavy influence of objects like dictionaries and lists on this notation, the Python language works very efficiently with such data.

In Python, we have the json library that contains a wide range of functionalities to work with such type of data. JSON serialization means taking some data and converting it into a JSON string. In Python, this can be achieved using the json.dumps() function.

When we get the object of type datetime is not JSON serializable exception in Python, it means that the datetime object cannot be serialized into a JSON string. This is a TypeError which means that it is caused due to performing illegal function on the given type of data.

Let us see an example of this exception.

import json
from datetime import datetime
dt = datetime(2022,5,9,15,20,15)
c = {'Date':dt, 'Name': 'Jack'}
s = json.dumps(c)
print(s)

Output:

TypeError: Object of type datetime is not JSON serializable

In the above example, we try to serialize a dictionary but the error is thrown because the dictionary contains a datetime object.

However, we can work around this and solve this exception using different ways.

💡 Quick fix

If you are looking for quick fix, you can just use default parameter with json.dumps() to fix the issue.

s = json.dumps(c, default = str);

Fix the object of type datetime is not JSON serializable exception in Python

The following section will discuss the different methods to fix the object of type datetime is not JSON serializable exception in Python.

Using the default parameter in the json.dumps() function

As discussed, the json.dumps() function is used to serialize some data to a JSON string. This function accepts a default parameter.

This parameter accepts a function that is applied to the object in case any TypeError exception is thrown. By using default parameter, the datetime object can be converted to a string by specifying the value of the parameter as the str function.

See the following example.

import json
from datetime import datetime
dt = datetime(2022,5,9,15,20,15)
c = {'Date':dt, 'Name': 'Jack'}
s = json.dumps(c, default = str)
print(s)

Output:

{“Date”: “2022-05-09 15:20:15”, “Name”: “Jack”}

In the above example, we can see that the exception is avoided due to the presence of the default parameter and the datetime object gets converted to a string.

Another function, we can use is the datetime.isoformat() method. This method returns a provided datetime object as a string in the ISO format. We can use this method instead of the str function.

See the following example.

import json
from datetime import datetime
def fun(ob):
    if isinstance(ob, datetime):
            return ob.isoformat()
dt = datetime(2022,5,9,15,20,15)
c = {'Date':dt, 'Name': 'Jack'}
s = json.dumps(c, default = fun)
print(s)

{“Date”: “2022-05-09 15:20:15”, “Name”: “Jack”}

In the above example, we create a function fun that takes an object and if this object is of type datetime (checked using the isinstance() method) then it returns a string of this object in ISO format using the isoformat() method.

Using the cls parameter in the json.dumps() function

We can use the cls parameter in the json.dumps() function to serialize incompatible types. We will create a subclass of the json.JSONEncoder class that by default manages this. We will override the default method and convert the datetime object to a string using the str method.

For example,

import json
from datetime import datetime
class DatetimeEncoder(json.JSONEncoder):
    def default(self, ob):
        if isinstance(ob, datetime):
            return str(ob)
        return json.JSONEncoder.default(self, ob)
dt = datetime(2022,5,9,15,20,15)
c = {'Date':dt, 'Name': 'Jack'}
s = json.dumps(c, cls = DatetimeEncoder)
print(s)

Output:

{“Date”: “2022-05-09 15:20:15”, “Name”: “Jack”}

The DatetimeEncoder class in the above example is a subclass of the json.JSONEncoder class. We define the default method to convert the datetime objects to strings.

Alternatively, we can also use the isoformat() method instead of the str function to get a string representation of the datetime object.

Using the str function

In the previous methods, we discussed how to get a string representation of the datetime object when encountered in the json.dumps() function. However, we can also just convert the object to a string directly before passing it for serialization using the str() function.

For example,

import json
from datetime import datetime
dt = datetime(2022,5,9,15,20,15)
c = {'Date':str(dt), 'Name': 'Jack'}
s = json.dumps(c)
print(s)

Output:

{“Date”: “2022-05-09 15:20:15”, “Name”: “Jack”}

Also, we can get the string representation using the isoformat() method.

Conclusion

To conclude, we discussed how to fix the object of type datetime is not JSON serializable exception in Python. We discussed several methods to tackle this error.

In the first method, we used specified the default parameter with the str and isoformat() functions to convert the datetime object to a string when encountered in the json.dumps() function.

Similarly, in the second method, we created a subclass of the json.JSONEncoder class that has a default method that handles datetime object in a similar way. We can also convert these objects beforehand as discussed in the final method.

]]>
https://java2blog.com/typeerror-object-of-type-datetime-is-not-json-serializable-python/feed/ 0
[Fixed] SyntaxError: Unexpected Character After Line Continuation Character https://java2blog.com/syntaxerror-unexpected-character-after-line-continuation-character/?utm_source=rss&utm_medium=rss&utm_campaign=syntaxerror-unexpected-character-after-line-continuation-character https://java2blog.com/syntaxerror-unexpected-character-after-line-continuation-character/#respond Tue, 01 Feb 2022 12:03:57 +0000 https://java2blog.com/?p=18963 While programming in python, sometimes we need to write very long statements. For better presentation, we often use line continuation character. However, if you don’t use line continuation character correctly, SyntaxError occurs with the message “SyntaxError: unexpected character after line continuation character in python”. In this article, we will discuss the possible cases when this error can occur and how you can overcome this syntax error.

What Is a Line Continuation Character in Python?

The escape character \ is used as the line continuation character in python. We often use the line continuation character to split a statement as shown below.

number1=10
number2=20
number3=30  
number4=40
number5=50
output=number1+number1*number2+number3*number1*number2\
+number4*number5
print("The output is:",output)

Output:

The output is: 8210

We can also split a single string into multiple lines using the line continuation character as follows.

myStr = "Hi am a long string. I am so long that I cannot fit into a single line in the source code." \
        "So, they have moved us to the next  line."
print(myStr)

Output:

Hi am a long string. I am so long that I cannot fit into a single line in the source code.So, they have moved us to the next  line.

Let us now discuss the situations where using the line continuation character leads to error. 

Syntaxerror: “Unexpected Character After Line Continuation Character in Python”- Occurrences and Solutions

Using escape character \ instead of the division operator / in mathematical expressions

The most common case when the syntax error occurs with the message “unexpected character after line continuation character in python” occurs when we use the escape character \ instead of the division operator / in mathematical expressions. You can observe this in the following example. 

num1=10
num2=5
output=num1\num2

Output:

/usr/lib/python3/dist-packages/requests/__init__.py:89: RequestsDependencyWarning: urllib3 (1.26.7) or chardet (3.0.4) doesn't match a supported version!
  warnings.warn("urllib3 ({}) or chardet ({}) doesn't match a supported "
  File "/home/aditya1117/PycharmProjects/pythonProject/string1.py", line 3
    output=num1\num2
                   ^
SyntaxError: unexpected character after line continuation character

This kind of error is mostly committed by new programmers who are just getting along with the syntax of the programming language. In this case, you can easily avoid this error using the division operator instead of the line continuation character as follows.

num1 = 10
num2 = 5
output = num1 / num2
print(output)

Output:

2.0

Adding the newline character \n to a string using the + operator

Sometimes, you may add the newline character \n to a string using the + operator as follows.

myStr = "Hi am a long string."
print(myStr+\n)

Output:

/usr/lib/python3/dist-packages/requests/__init__.py:89: RequestsDependencyWarning: urllib3 (1.26.7) or chardet (3.0.4) doesn't match a supported version!
  warnings.warn("urllib3 ({}) or chardet ({}) doesn't match a supported "
  File "/home/aditya1117/PycharmProjects/pythonProject/string1.py", line 2
    print(myStr+\n)
                  ^
SyntaxError: unexpected character after line continuation character

Here, we have tried to print a new line along with the string by adding it to the string. However, this leads to syntax error saying “unexpected character after line continuation character in python”. This is so because \n works as the newline character only when it is used as a string literal. In this case, \ is considered as a line continuation character, and n is considered to be an unexpected character because there are no characters allowed after a line continuation character. In this case, you can avoid the syntax error by simply using the newline character as a string as shown in the following example.

myStr = "Hi am a long string."
print(myStr+"\n")

Output:

Hi am a long string.

Adding space or tab after the line continuation character

In the above two cases, the errors are easily identifiable. However, if it happens that you put a space or tab after the line continuation character, the program will again run into the syntax error and will display the error message “unexpected character after line continuation character in python”. For instance, look at the example below.

number1=10
number2=20
number3=30  
number4=40
number5=50
output=number1+number1*number2+number3*number1*number2\ 
+number4*number5
print("The output is:",output)

Output:

/usr/bin/python3.8 /home/aditya1117/PycharmProjects/pythonProject/string1.py
/usr/lib/python3/dist-packages/requests/__init__.py:89: RequestsDependencyWarning: urllib3 (1.26.7) or chardet (3.0.4) doesn't match a supported version!
  warnings.warn("urllib3 ({}) or chardet ({}) doesn't match a supported "
  File "/home/aditya1117/PycharmProjects/pythonProject/string1.py", line 6
    output=number1+number1*number2+number3*number1*number2\ 
                                                           ^
SyntaxError: unexpected character after line continuation character

Here, you cannot identify that there is a space character after the line continuation character. However, the space character is present and it has caused the syntax error in the program. So, if you are facing a syntax error with the message “unexpected character after line continuation character in python” and you are not able to identify what the mistake is, make sure that you press the enter key just after the line continuation character and there are no spaces after it. IN this way, you will be able to remove the syntax error.

Conclusion

In this article, we have discussed how the syntax error with the message “SyntaxError: unexpected character after line continuation character in python” occurs and how we can avoid it. 

I hope you enjoyed reading this article. Stay tuned for more informative articles.

Happy Learning!

]]>
https://java2blog.com/syntaxerror-unexpected-character-after-line-continuation-character/feed/ 0
[Fixed] Object of Type int64 Is Not JSON Serializable https://java2blog.com/object-of-type-int64-is-not-json-serializable/?utm_source=rss&utm_medium=rss&utm_campaign=object-of-type-int64-is-not-json-serializable https://java2blog.com/object-of-type-int64-is-not-json-serializable/#respond Tue, 01 Feb 2022 11:51:13 +0000 https://java2blog.com/?p=18965 JSON objects are used extensively in data transmission or in data interchange between different languages. To transmit data, we often convert the data to JSON objects. After that, we transmit the data. Sometimes, while creating a JSON object, your program might run into the TypeError exception with the message “object of type int64 is not json serializable”. IN this article, we will discuss how we can avoid this error.

How Do We Create JSON Objects in Python?

In python, we create a JSON object using the dumps() method defined in the json module. The dumps() method takes a python object as its input argument and returns a JSON string after execution. You can observe this in the following example.

import json

x = 1117
print("The input value is:", x)
print("Data type of input is:", type(x))
y = json.dumps(x)
print("The output value is:", y)
print("Data type of output is:", type(y))

Output:

The input value is: 1117
Data type of input is: <class 'int'>
The output value is: 1117
Data type of output is: <class 'str'>

In the output, you can observe that the input number is converted into a json string by the dumps() method. You can also convert a collection object like a list or dictionary to json string using the dumps() method as follows.

import json

myList = [1, 2, 3, 4, 5, 6, 7]
print("The input list is:", myList)
print("Data type of input is:", type(myList))
y = json.dumps(myList)
print("The output value is:", y)
print("Data type of output is:", type(y))
myDict = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49}
print("The input dictionary is:", myDict)
print("Data type of input is:", type(myDict))
y = json.dumps(myDict)
print("The output value is:", y)
print("Data type of output is:", type(y))

Output:

The input list is: [1, 2, 3, 4, 5, 6, 7]
Data type of input is: <class 'list'>
The output value is: [1, 2, 3, 4, 5, 6, 7]
Data type of output is: <class 'str'>
The input dictionary is: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49}
Data type of input is: <class 'dict'>
The output value is: {"1": 1, "2": 4, "3": 9, "4": 16, "5": 25, "6": 36, "7": 49}
Data type of output is: <class 'str'>

We also use the dump() method to create a JSON object from a python object. The dump() method takes the python object as its first argument and a file object as its second input argument. After execution, it creates a JSON object and appends it to the file that is represented by the file object. You can observe this in the following example.

import json

myFile = open("sample.txt", "w")
myList = [1, 2, 3, 4, 5, 6, 7]
print("The input list is:", myList)
print("Data type of input is:", type(myList))
json.dump(myList, myFile)
myDict = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49}
print("The input dictionary is:", myDict)
print("Data type of input is:", type(myDict))
json.dump(myDict, myFile)
myFile.close()
# read the content after saving the file.
myFile = open("sample.txt", "r")
content = myFile.read()
print("The content in the file is:")
print(content)

Output:

The input list is: [1, 2, 3, 4, 5, 6, 7]
Data type of input is: <class 'list'>
The input dictionary is: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49}
Data type of input is: <class 'dict'>
The content in the file is:
[1, 2, 3, 4, 5, 6, 7]{"1": 1, "2": 4, "3": 9, "4": 16, "5": 25, "6": 36, "7": 49}

You can observe that the output by the dumps() method is similar to the dump() method. However, the dump() method saves the output in a file and the dumps() method returns the output as a string.

What Is JSON Serializable Object?

In python, not all data types can be converted into JSON format. For instance, we can only convert the data types including int, dict, list, str, int, float, and the values True, False, and None to JSON format.

Objects with any other datatype are not json serializable and cannot be converted to JSON format.

Typeerror: Object of Type int64 Is Not Json Serializable- Causes 

When we pass an object of the data type that is not serializable to the dump() or dumps() method, the program runs into the TypeError exception. The int64 data type is not a serializable data type and when we try to pass it to the dumps() method, the program runs into the TypeError exception and shows the message “object of type int64 is not json serializable”. You can observe this in the following example. 

import json
import numpy

x = numpy.int64(1117)
print("The input value is:", x)
print("Data type of input is:", type(x))
y = json.dumps(x)
print("The output value is:", y)
print("Data type of output is:", type(y))

Output:

The input value is: 1117
Data type of input is: <class 'numpy.int64'>
Traceback (most recent call last):
  File "/home/aditya1117/PycharmProjects/pythonProject/string1.py", line 7, in <module>
    y = json.dumps(x)
  File "/usr/lib/python3.8/json/__init__.py", line 231, in dumps
    return _default_encoder.encode(obj)
  File "/usr/lib/python3.8/json/encoder.py", line 199, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "/usr/lib/python3.8/json/encoder.py", line 257, in iterencode
    return _iterencode(o, 0)
  File "/usr/lib/python3.8/json/encoder.py", line 179, in default
    raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type int64 is not JSON serializable

Even if an integer of the type int64 is present in another object like a dictionary, the TypeError exception will occur with the message “TypeError: Object of type int64 is not JSON serializable”. You can observe this in the following example.

import json
import numpy

x = numpy.int64(1117)
myDict = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: x}
print("The input dictionary is:", myDict)
print("Data type of input is:", type(myDict))
y = json.dumps(myDict)
print("The output value is:", y)
print("Data type of output is:", type(y))

Output:

The input dictionary is: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 1117}
Data type of input is: <class 'dict'>
/usr/lib/python3/dist-packages/requests/__init__.py:89: RequestsDependencyWarning: urllib3 (1.26.7) or chardet (3.0.4) doesn't match a supported version!
  warnings.warn("urllib3 ({}) or chardet ({}) doesn't match a supported "
Traceback (most recent call last):
  File "/home/aditya1117/PycharmProjects/pythonProject/string1.py", line 8, in <module>
    y = json.dumps(myDict)
  File "/usr/lib/python3.8/json/__init__.py", line 231, in dumps
    return _default_encoder.encode(obj)
  File "/usr/lib/python3.8/json/encoder.py", line 199, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "/usr/lib/python3.8/json/encoder.py", line 257, in iterencode
    return _iterencode(o, 0)
  File "/usr/lib/python3.8/json/encoder.py", line 179, in default
    raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type int64 is not JSON serializable

Typeerror: Object of Type int64 Is Not Json Serializable- Solutions

Any data type defined in the numpy module isn’t serializable. So, whenever you are using libraries like scipy, numpy, or pandas, you might run into this error while converting the python objects to JSON objects.

To avoid Typeerror: Object of Type int64 Is Not Json Serializable, you can first convert the numpy objects to normal int and float objects before creating a JSON object.

Here is an example:
import json
import numpy

x = numpy.int64(1117)
print("The input value is:", x)
print("Data type of input is:", type(x))
y = json.dumps(int(x))
print("The output value is:", y)
print("Data type of output is:", type(y))

Output:

The input value is: 1117
Data type of input is: <class 'numpy.int64'>
The output value is: 1117
Data type of output is: <class 'str'>

Instead of manually converting each python object to the serializable data type, you can define a class that inherits the JSONEncoder class to convert the numpy objects into serializable objects. After that, you can pass the class to the dump() method or the dumps() method using the cls parameter. In this way, whenever a data type such as int64 is encountered, it will be converted to int datatype. Similarly, other numpy objects will be converted to corresponding serializable data types and the program will not run into TypeError exception. You can observe this in the following example.

import json
import numpy


class NpEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, numpy.integer):
            return int(obj)
        if isinstance(obj, numpy.floating):
            return float(obj)
        if isinstance(obj, numpy.ndarray):
            return obj.tolist()
        return super(NpEncoder, self).default(obj)


x = numpy.int64(1117)
print("The input value is:", x)
print("Data type of input is:", type(x))
y = json.dumps(x, cls=NpEncoder)
print("The output value is:", y)
print("Data type of output is:", type(y))

Output:

The input value is: 1117
Data type of input is: <class 'numpy.int64'>
The output value is: 1117
Data type of output is: <class 'str'>

While using an encoder class, you can even convert collection objects containing non-serializable data types to JSON very easily as follows.

import json
import numpy


class NpEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, numpy.integer):
            return int(obj)
        if isinstance(obj, numpy.floating):
            return float(obj)
        if isinstance(obj, numpy.ndarray):
            return obj.tolist()
        return super(NpEncoder, self).default(obj)


x = numpy.int64(1117)
myDict = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: x}
print("The input dictionary is:", myDict)
print("Data type of input is:", type(myDict))
y = json.dumps(myDict, cls=NpEncoder)
print("The output value is:", y)
print("Data type of output is:", type(y))

Output:

The input dictionary is: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 1117}
Data type of input is: <class 'dict'>
The output value is: {"1": 1, "2": 4, "3": 9, "4": 16, "5": 25, "6": 36, "7": 1117}
Data type of output is: <class 'str'>

In the output, you can observe that the dictionary containing an integer of type int64 has been converted to JSON without an error. This is due to the reason that we have used the encoder class that converts the integer data types defined in the numpy module to the simple integer type.

Conclusion

In this article, we have discussed how JSON objects are created in python and why the message “TypeError: object of type int64 is not json serializable” is shown. If you are using numpy, scipy, pandas, or any other module that is created on the top of the numpy module, you should use the encoder function that we created in the last example to avoid the TypeError exception.

I hope you enjoyed reading this article. Stay tuned for more informative articles.

Happy Learning! 

]]>
https://java2blog.com/object-of-type-int64-is-not-json-serializable/feed/ 0
[Fixed] ValueError: too many values to unpack (expected 2) https://java2blog.com/valueerror-too-many-values-to-unpack-python/?utm_source=rss&utm_medium=rss&utm_campaign=valueerror-too-many-values-to-unpack-python https://java2blog.com/valueerror-too-many-values-to-unpack-python/#respond Fri, 10 Dec 2021 10:50:11 +0000 https://java2blog.com/?p=18494 While programming in python, we can assign values to two or more variables in a single statement. While doing so, you might get the ValueError exception with the message “ValueError: too many values to unpack ”. If you are trying to assign values to two variables at the same time, you will get the message “ValueError: too many values to unpack (expected 2)”. In this article, we will see why this exception occurs and how we can resolve it.

What is unpacking in python?

When we have a container object like a list, tuple, set, or dictionary, we can assign the elements of the container object directly to variables. Suppose that you have a list containing n elements. You can assign the elements to n variables in a single statement as follows.

var1,var2,var3,var4...., varN=[element1,element2,element3,element4..., elementN]

This process of assigning the elements of a container object to variables is called unpacking in python. In other words, we unpack the elements from the container and assign them to different variables. You can observe this in the following example.

myList = [1, 2, 3, 4]
print("The list is:", myList)
var1, var2, var3, var4 = myList
print("var1 is:", var1)
print("var2 is:", var2)
print("var3 is:", var3)
print("var4 is:", var4)

Output:

The list is: [1, 2, 3, 4]
var1 is: 1
var2 is: 2
var3 is: 3
var4 is: 4

In the above example, we have a list named myList having 4 elements in it. In the expression var1, var2, var3, var4 = myList , we have unpacked all the elements of the list into var1,var2,var3, and var4. The elements of the list are assigned to the variables in their respective order. i.e. The first variable gets the first element, the second variable gets the second element, and so on.

What is ValueError: too many values to unpack (expected 2)?

While unpacking, we have to make sure that the number of variables should be equal to the number of elements in the container object. However, if we unpack a container object and assign it to fewer variables than the elements present in the container object, it will raise the ValueError exception with the message ValueError: too many values to unpack. For instance, if we have a list with four elements and we assign it only to three elements, it will raise the ValueError exception as follows.

myList = [1, 2, 3, 4]
print("The list is:", myList)
var1, var2, var3= myList
print("var1 is:", var1)
print("var2 is:", var2)
print("var3 is:", var3)

Output:

The list is: [1, 2, 3, 4]
Traceback (most recent call last):
  File "/home/aditya1117/PycharmProjects/pythonProject/string1.py", line 3, in <module>
    var1, var2, var3= myList
ValueError: too many values to unpack (expected 3)

You can observe that in the case of a lesser number of variables than the elements in the container object, the program raises the ValueError exception. For instance, we have tried to assign a list with more elements to three variables var1, var2, and var3. This results in an error with the message ValueError: too many values to unpack (expected 3).

If we assign the elements of a list to only two variables and the list happens to contain more than two elements, it will raise the ValueError exception with the message ValueError: too many values to unpack (expected 2) as follows.

myList = [1, 2, 3, 4]
print("The list is:", myList)
var1, var2= myList
print("var1 is:", var1)
print("var2 is:", var2)

Output:

The list is: [1, 2, 3, 4]
Traceback (most recent call last):
  File "/home/aditya1117/PycharmProjects/pythonProject/string1.py", line 3, in <module>
    var1, var2= myList
ValueError: too many values to unpack (expected 2)

Similarly, if we assign the elements of a tuple, dictionary, or set to two variables and the number of elements is more than 2, the program will raise the ValueError exception with the message ValueError: too many values to unpack (expected 2).

One more situation where this kind of ValueError exception occurs when we work with dictionaries. Generally, beginners think that we can extract keys and values from a dictionary and print them as follows.

myDict = {"name": "Java2blog", "website": "java2blog.com", "language": "python"}
for key, value in myDict:
    print(key)
    print(value)

However, this will lead to the ValueError exception as follows.

Traceback (most recent call last):
  File "/home/aditya1117/PycharmProjects/pythonProject/string1.py", line 2, in <module>
    for key, value in myDict:
ValueError: too many values to unpack (expected 2)

Here, the user thinks that in each iteration of the for loop, a key and a value from myDict will be assigned to the variable key and the variable value. However, this doesn’t happen. In the for loop, myDict works as an iterable object that has the keys of the dictionary in it. In the first execution of the for loop, the string “name” from myDict is assigned to the variables key and value in the for loop. As there are four characters in the string “name“, the unpacking operation fails and the exception is raised with the message ValueError: too many values to unpack (expected 2). Had there been only two characters in the keys of the dictionary, the above for loop will run without any error. However, it won’t produce the desired result. You can observe this in the following example.

myDict = {"na": "Java2blog", "ws": "java2blog.com", "ln": "python"}
for key, value in myDict:
    print(key)
    print(value)

Output:

n
a
w
s
l
n

In the above output, you can observe that the variables key and value in the for loop are assigned characters from the strings in the keys of the dictionary. They are not assigned the actual keys and values of the dictionary. Hence, the above code makes no sense, although it executes without any error.

How to resolve ValueError: too many values to unpack (expected 2)?

To avoid the ValueError exception with the message “ValueError: too many values to unpack (expected 2)”, you should make sure that you should use the same number of variables as the elements in the container object while unpacking. For instance, if you have two variables, you should only unpack a container object with only two elements as follows.

myList = [1, 2]
print("The list is:", myList)
var1, var2 = myList
print("var1 is:", var1)
print("var2 is:", var2)

Output:

The list is: [1, 2]
var1 is: 1
var2 is: 2

While working with dictionaries, you should use the items() method to iterate through the keys and values of the dictionary as follows.

myDict = {"name": "Java2blog", "website": "java2blog.com", "language": "python"}
for key, value in myDict.items():
    print(key)
    print(value)

Output:

name
Java2blog
website
java2blog.com
language
python

Here, the items() method returns a list of tuples. Each tuple contains two elements where the first element is a key of the dictionary and the second element of the tuple is the associated value. Hence, In each iteration of the for loop, a tuple is unpacked and the values are assigned to the variables key and value.

Conclusion

In this article, we discussed why we get the error with the message ValueError: too many values to unpack (expected 2) in python. We also discussed how we can avoid this error in our program. To make sure that you don’t run into this error, you just have to unpack the container objects to the same number of variables as the number of elements in the container object like list, set, or tuple.

I hope you enjoyed reading this article. Stay tuned for more informative articles.

Happy Learning!

]]>
https://java2blog.com/valueerror-too-many-values-to-unpack-python/feed/ 0
How to check if variable exists in Python https://java2blog.com/check-if-variable-exists-python/?utm_source=rss&utm_medium=rss&utm_campaign=check-if-variable-exists-python https://java2blog.com/check-if-variable-exists-python/#respond Wed, 14 Apr 2021 14:45:46 +0000 https://java2blog.com/?p=13819 Introduction

Objective: This article will discuss the different methods to check if a variable exists in Python.

Before we dive into the methods to check for the availability of a variable in the code, let us first understand why we need to do so? 🤔

To answer the above question, you must understand “what is a NameError and an UnboundLocalError in Python?

🐞 NameError and UnboundLocalError in Python

📌 In Python, if you try to access or interact with a variable name that is not defined, you get NameError: name 'variable_name' is not defined exception.

Example:

numbers = [30,40,25,70,50,35]
num=40
for x in numbers:
    if x > num:
        add_up += 1
print(add_up)

Output:

Traceback (most recent call last):
File “main.py”, line 5, in
add_up += 1
NameError: name ‘add_up’ is not defined

❖ Since the variable with name ‘add_up’ is not defined in our code in the above example, we got a NameError.

📌 Similarly, you get UnboundLocalError: local variable 'variable_name' referenced before assignment exception when you refer a local variable before assigning it in your program.

Example:

# Program to find the average of a number
def total(num):
    l = len(num)
    for x in num:
        avg += x / l
    return avg


numbers = [30, 10, 60, 20]
print('Average = ', total(numbers))

Output:

Traceback (most recent call last):
File “main.py”, line 10, in
print(‘Average = ‘, total(numbers))
File “main.py”, line 5, in total
avg += x / l
UnboundLocalError: local variable ‘avg’ referenced before assignment

❖ We got UnboundLocalError exception because the local variable with the name ‘avg’ was referenced before being assigned in the program.

⚡ Thus, the aforementioned exceptions occur primarily due to the following reasons:-
➥ If you forget to define a variable.
➥ If you use the wrong variable name.
➥ Or if you try to access a variable before defining it.

Both of these errors are pretty common, especially for newbies. To fix them, you can simply edit your program and manually define the variable that leads to the occurrence of these errors.

However, if your code is quite lengthy, then it can be extremely tedious to spot every undefined variable one by one in your program. This is where you can check if a variable exists in the first place before using it.

Read Here: [Solved] ValueError: could not convert string to float

Hence, without further delay, let us discuss the methods to check if a variable exists in the Python code.

✨ Method 1: Using locals() and globals()

locals() and globals() are built-in functions in Python that can be used to check for the availability of an identifier. Both these functions return the local and global symbol table, respectively. Thus, you can simply check if a variable exists locally or globally using the respective symbol tables.

Solution:

a = 0


def check():
    c = 0
    if 'a' in globals():  # checking for variable named 'a' in global variables
        print(True)
        if 'b' in locals():  # checking for 'b' in local variables
            print(True)
        else:
            print(False)
    if 'c' in locals():
        print(True)


check()

Output:

True
False
True

✨ Method 2: Using dir({object})

dir({object}) is a built-in method in Python that returns the list of methods and attributes of the specified object.

Solution: Let’s incorporate the dir() method to fix the NameError in the example mentioned previously.

numbers = [30, 40, 25, 70, 50, 35]
num = 40
for x in numbers:
    if x > num:
        if 'add_up' in dir():  # checking for variable in list of names
            add_up += 1
        else:
            add_up = 1

print("No. of values > {} = {}".format(num, add_up))

Output:

No. of values > 40 = 2

✨ Method 3: Using try and except Block

The try and except blocks are one of the most effective solutions when you have to deal with exception handling in Python. You can implement the error code in the try block and handle it in the except block.

Example:

def total(num):
    l = len(num)
    for x in num:
        try:
            avg += x / l  # error code
        except:
            avg = x / l  # exception handling code
    return avg


numbers = [30, 10, 60, 20]
print('Average = ', total(numbers))

Output:

Average = 30.0

✨ Method 4: Using vars([object])

  • vars() is another built-in method in Python that returns the __dict__ attribute for a module, class, instance, or any other object with a __dict__ attribute. Here, __dict__ refers to the dictionary that stores an object’s (writable) attribute.
  • Without any arguments, the vars() acts just like locals() method and returns a dictionary of the current namespace.

Solution: Let’s implement this method to fix the UnboundLocalError in the example mentioned previously.

def total(num):
    l = len(num)
    for x in num:
        if 'avg' in vars():  # checking for 'avg' in __dict__ using vars() method
            avg += x / l
        else:
            avg = x / l
    return avg


numbers = [30, 10, 60, 20]
print('Average = ', total(numbers))

Output:

Average = 30.0

__dict__

You can also directly check for a variable using the __dict__ attribute of class or module, or instance.

Example:

# Checking for existing variables in a class named Variables
class Variables():
    def __init__(self, a):
        self.a = a
        self.check()

    def check(self):
        if 'a' in self.__dict__:  # accessing __dict__ with class object
            print('a =', self.a)
        else:
            print("'a' is not defined")
        if 'b' in self.__dict__:
            print('b =', self.b)
        else:
            print("b is not defined")


obj = Variables(1)

Output:

a = 1
b is not defined

Thus, we were able to check for the existence of multiple variables using __dict__ in our example given above.

Conclusion

Let us recall the key points that were discussed in this article:
✔ NameError and UnboundLocalError
✔ Methods to check if a variable exists and resolve the above errors.

Please subscribe and stay tuned for more discussions and solutions in the future.

Authors:
👨‍🎓 ANIRBAN CHATTERJEE
👨‍🎓
SHUBHAM SAYON

]]>
https://java2blog.com/check-if-variable-exists-python/feed/ 0