Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

Python json.__all__ Attribute



The Python json.__all__ attribute is a list that defines the public API of the json module, specifying the names that are exported when from json import * is used.

This attribute helps in controlling what gets imported into the namespace when performing a wildcard import.

Syntax

Following is the syntax for accessing the json.__all__ attribute −

import json

# Access the __all__ attribute
print(json.__all__)

Contents of json.__all__

The json.__all__ attribute includes the following key components of the json module −

  • dump: Function to serialize Python objects to a file-like object.
  • dumps: Function to serialize Python objects to a JSON-formatted string.
  • load: Function to deserialize JSON from a file-like object.
  • loads: Function to deserialize JSON from a string.
  • JSONDecoder: Class for decoding JSON-encoded strings.
  • JSONEncoder: Class for encoding Python objects into JSON.

Example: Accessing json.__all__

In this example, we access the json.__all__ attribute to see its contents −

import json

# Print the contents of json.__all__
print("Public API of json module:", json.__all__)

Following is the output obtained −

Public API of json module: ['dump', 'dumps', 'load', 'loads', 'JSONDecoder', 'JSONDecodeError', 'JSONEncoder']

Example: Using from json import *

Using from json import * imports only the names listed in json.__all__

from json import *

# Using dumps function from json module
json_string = dumps({"name": "Alice", "age": 25})
print("Serialized JSON:", json_string)

Following is the output of the above code −

Serialized JSON: {"name": "Alice", "age": 25}

Example: Checking if a Name is in json.__all__

We can check if a function or class is part of the public API −

import json

# Check if 'JSONEncoder' is in json.__all__
print("Is 'JSONEncoder' in json.__all__?", 'JSONEncoder' in json.__all__)

We get the output as shown below −

Is 'JSONEncoder' in json.__all__? True

Example: Checking if a Function is in json.__all__

The json.__all__ attribute contains a list of publicly available functions in the json module. You can check if a specific function exists within this attribute using the in keyword −

import json

# Check if 'dumps' is available in json.__all__
if "dumps" in json.__all__:
   print("dumps function is available in json module.")

# Check if 'loads' is available in json.__all__
if "loads" in json.__all__:
   print("loads function is available in json module.")

The result produced is as follows −

dumps function is available in json module.
loads function is available in json module.
python_json.htm
Advertisements