Python Func Basestring
# Python basestring() Function
In Python, understanding how different data types relate to one another is crucial for writing robust, type-safe code. This tutorial covers the built-in `basestring()` function, its purpose in Python 2, and how to handle its deprecation in Python 3.
---
## Description
The `basestring()` function is an abstract superclass (parent class) of both `str` and `unicode`. Because it is an abstract class, you cannot instantiate or call it directly.
Its primary purpose is to serve as a helper for type checking. It allows you to determine whether an object is an instance of either `str` or `unicode`.
Using `isinstance(obj, basestring)` is functionally equivalent to writing `isinstance(obj, (str, unicode))`.
> **Important Note:** The `basestring()` function is **only available in Python 2**. It has been completely removed in Python 3, where all strings are unified under the `str` type.
---
## Syntax
Since `basestring` is an abstract class, it does not have a callable constructor. However, it is referenced in type-checking syntax as follows:
```python
isinstance(object, basestring)
```
### Parameters
* **object**: The object you want to inspect.
### Return Value
* Returns `True` if the object is an instance of `str` or `unicode` (in Python 2).
* Returns `False` otherwise.
* Raises a `TypeError` if you attempt to instantiate it directly (e.g., `basestring()`).
---
## Code Examples
### Basic Usage in Python 2
The following interactive shell example demonstrates how `basestring` behaves in a Python 2 environment:
```python
# Check if a standard string is an instance of str
>>> isinstance("Hello World", str)
True
# Check if a standard string is an instance of basestring
>>> isinstance("Hello World", basestring)
True
# Check if a unicode string is an instance of basestring
>>> isinstance(u"Hello World", basestring)
True
# Attempting to instantiate basestring directly raises an error
>>> basestring()
Traceback (most recent call last):
File "", line 1, in
TypeError: The basestring class cannot be instantiated
```
---
## Python 3 Compatibility and Alternatives
In Python 3, the distinction between `str` (ASCII/bytes in Python 2) and `unicode` was eliminated. In Python 3, all text strings are Unicode by default and represented by the `str` class, while binary data is represented by the `bytes` class.
Consequently, **`basestring` does not exist in Python 3**. If you try to use it, Python will raise a `NameError`.
### How to write cross-compatible code
If you are writing code that needs to run on both Python 2 and Python 3, you can use the following patterns to handle string type checking safely:
#### Method 1: Try-Except Block (Recommended for Libraries)
You can define a compatibility alias at the top of your module:
```python
try:
# Python 2 compatibility
string_types = (basestring,)
except NameError:
# Python 3 compatibility
string_types = (str,)
# Usage
my_var = "Hello World"
if isinstance(my_var, string_types):
print("This is a valid string!")
```
#### Method 2: Using the `six` Compatibility Library
If your project uses the `six` library for Python 2/3 compatibility, you can use `six.string_types`:
```python
import six
my_var = "Hello World"
if isinstance(my_var, six.string_types):
print("This is a valid string!")
```
YouTip