Your first example is perfectly fine. Even the official Python documentation recommends this style known as EAFP.
Personally, I prefer to avoid nesting when it’s not necessary:
def __getattribute__(self, item): try: return object.__getattribute__(item) except AttributeError: pass # Fallback to dict try: return self.dict[item] except KeyError: raise AttributeError("The object doesn't have such attribute") from None
PS. has_key()
has been deprecated for a long time in Python 2. Use item in self.dict
instead.
Related Posts:
- python capitalize first letter only
- Is there a short contains function for lists?
- ImportError: No module named pandas. Pandas installed pip
- How to Execute a Python Script in Notepad++?
- ValueError: operands could not be broadcast together with shapes (5,) (30,)
- appending list but error ‘NoneType’ object has no attribute ‘append’
- Using Python 3 in virtualenv
- “Series objects are mutable and cannot be hashed” error
- Putting a simple if-then-else statement on one line [duplicate]
- matplotlib savefig() plots different from show()
- Converting list to numpy array
- How do I parse a string to a float or int?
- Check if something is (not) in a list in Python
- How to parse data in JSON format?
- TypeError: unhashable type: ‘dict’
- ‘Conda’ is not recognized as internal or external command
- Python list of dictionaries search
- Extract file name from path, no matter what the os/path format
- Permission denied error by installing matplotlib
- Python equivalent of a given wget command
- How to find list intersection?
- Error while Executing jupyter notebook: [Errno 2] No such file or directory
- ValueError: max() arg is an empty sequence
- How do I insert a JPEG image into a python Tkinter window?
- Use a.any() or a.all()
- What is the difference between Spyder and Jupyter?
- What is the maximum recursion depth in Python, and how to increase it?
- subprocess.check_output return code
- Is arr.__len__() the preferred way to get the length of an array in Python?
- Running Python from Atom
- TypeError: can’t use a string pattern on a bytes-like object in re.findall()
- gaierror: [Errno 8] nodename nor servname provided, or not known (with macOS Sierra)
- How to print colored text to the terminal
- TypeError: can only concatenate list (not “str”) to list
- What’s the idiomatic syntax for prepending to a short python list?
- What is the difference between “is None” and “== None”
- Why Python 3.6.1 throws AttributeError: module ‘enum’ has no attribute ‘IntFlag’?
- Creating 2D dictionary in Python
- Python: slicing a multi-dimensional array
- Python: pandas merge multiple dataframes
- Shuffle an array with python, randomize array item order with python
- How to count the NaN values in a column in pandas DataFrame
- How to install multiple python packages at once using pip
- Running Selenium with Headless Chrome Webdriver
- boto3 client NoRegionError: You must specify a region error only sometimes
- Converting Dictionary to List?
- pip3: command not found
- How to get keyboard input in pygame?
- How to use sys.exit() in Python
- How to get all possible combinations of a list’s elements?
- Converting strings to floats in a DataFrame
- Pylint “unresolved import” error in Visual Studio Code
- Errno 13 Permission denied Python
- ValueError: object too deep for desired array while using convolution
- How to convert string to binary?
- How to iterate through two lists in parallel?
- Make list of arrays in python
- In Python, what is `sys.maxsize`?
- Pyspark: Exception: Java gateway process exited before sending the driver its port number
- Converting from a string to boolean in Python?
- Import Error: No module named numpy Anaconda
- How to remove \n from a list element?
- How to add an empty column to a dataframe?
- Virtualenv Command Not Found
- How to stop a function
- What is the common header format of Python files?
- Is it possible to decompile a compiled .pyc file into a .py file?
- Writing string to a file on a new line every time
- Creating lowpass filter in SciPy – understanding methods and units
- Python 2: AttributeError: ‘list’ object has no attribute ‘strip’
- Get Confusion Matrix From a Keras Multiclass Model
- AttributeError: ‘list’ object has no attribute ‘lower’ gensim
- Insert a row to pandas dataframe
- Anaconda Installed but Cannot Launch Navigator
- How to save a Seaborn plot into a file
- How to get the unit vector from a numpy array
- Subtract two columns in dataframe
- Sending string via socket (python)
- pandas DataFrame: replace nan values with average of columns
- How do I disable “missing docstring” warnings at a file-level in Pylint?
- How to convert column with dtype as object to string in Pandas Dataframe
- When I use matplotlib in jupyter notebook,it always raise ” matplotlib is currently using a non-GUI backend” error?
- How to fix ‘RuntimeWarning: divide by zero encountered in double_scalars’
- IndexError: index 2 is out of bounds for axis 0 with size 2
- ‘if’ statement in jinja2 template
- Python name ‘os’ is not defined
- Python CSV Error: sequence expected
- How to set environment variables in PyCharm?
- How to pad zeroes to a string?
- ImportError: No module named ‘MySQL’
- Using unicode character u201c
- ERROR: Could not build wheels for cryptography which use PEP 517 and cannot be installed directly
- How to set NotebookApp.iopub_data_rate_limit and others NotebookApp settings in JupyterHub?
- TypeError: can only concatenate tuple (not “str”) to tuple Error
- ‘pyuic5’ is not recognized as an internal or external command
- ValueError: multiclass format is not supported
- Filtering a NumPy Array
- Invalid syntax when using “print”?
- Error loading MySQLdb module: No module named ‘MySQLdb’
- Unable to install boto3