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 513b6762 authored by vermeul's avatar vermeul
Browse files

Update 09-Subroutines.md

parent 95951a78
......@@ -62,6 +62,34 @@ It is not very elegant and adds unecessary infrastructure code into your functio
See also: https://docs.python-guide.org/writing/gotchas/
## Use an empty list or a dictionary to implement a state variable
An exception of the rule above is when you need to implement a state variable. A state variable is a permanent store of a value the first time a method or function gets executed. Here is an example for a password store which can only be executed by an inner method. This can be useful if you need the password later for reconnect to a server, without giving the possibility to easily get the cleartext password:
```
import inspect
class PW():
def get_password_via_internal_method(self, *args, **kwargs):
return self.password(*args, **kwargs)
def password(self, password=None, pstore={} ):
if password is not None:
pstore['password'] = password
else:
if inspect.stack()[1][3] == 'get_password_via_internal_method':
return pstore.get('password')
else:
raise Exception("Not allowed!")
# later
pw = PW()
pw.password('very_secret')
pw.get_password_via_internal_method() # returns the password
pw.password() # will throw an Exception
```
## Use docstrings to comment your code
* Classes, functions and methods should have doctrings
......
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