To receive notifications about scheduled maintenance, please subscribe to the mailing-list gitlab-operations@sympa.ethz.ch. You can subscribe to the mailing-list at https://sympa.ethz.ch

Commit 2abbb2e5 authored by vermeul's avatar vermeul
Browse files

Update 04-Values_and_Expressions.md

parent 36811599
# Values and Expressions
## Long strings
Code should not become longer than about 120 characters, but strings often get much longer. Use round brackets `( )` on mutltiple lines to create a long string:
```python
my_long_string = (
"Donau"
"dampfschiff"
"fahrts"
"gesellschafts"
"kapitän"
)
# will be automatically concatenated to Donaudampfschifffahrtsgesellschaftskapitän
```
## Multiline strings
If a string has embedded newline characters, you might define it this way:
......@@ -83,7 +99,7 @@ print(get_text())
</strong>
This will unfortunately break the indentation but is the least amount of typing.
## Avoiding Errors when accessing values
## Errors when accessing values in arrays, dictionaries and objects
In Python, various errors might occur when you try to access a non-existing value from a data structure:
......@@ -91,11 +107,13 @@ In Python, various errors might occur when you try to access a non-existing valu
* Dictionaries: **KeyError**
* Objects: **AttributeError**
We do not want to use the annoying `try ... except` structure all the time. We rather need a safe way to access values. Unfortunately has a different approach for every object:
We do not want to use the annoying `try ... except` structure all the time. We rather need a safe way to access values. Unfortunately, Python demands a different approach for every object:
**Array**
```
Accessing an element in an array which might be missing is particularly nasty:
```python
a = []
a[7] # IndexError
a[7] if len(a) > 7 else 'nothing here' # OK
......@@ -103,8 +121,20 @@ a[7] if len(a) > 7 else 'nothing here' # OK
**Dictionary**
```
Dictionaries offer a generic `get` method to safely access an item in a dictionary:
```python
dict = {}
dict['not_here] # KeyError
dict.get('not_here', 'alternative value') # ok
```
**Object**
Objects do not offer any specialized method to access internal attributes in a safe way. Instead, Python demands the generic `getattr` method. Make sure you offer an alternative value, otherwise an AttributeError will be thrown:
```python
my_object = SomeClass()
getattr(my_object, 'non_existing_attribute_name') # throws AttributeError
getattr(my_object, 'maybe_existing_attribute_name', None) # returns the value of the attribute (or None, if it does not exist)
```
\ No newline at end of file
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment