Python cheat sheet
# padding on the left
print("234".rjust(10, "0"))
# 0000000234
# padding on the right
print("234".ljust(10, "0"))
# 2340000000
class Foo:
def __init__(self):
self._value = None
@property
def value(self):
return self._value
@value.setter
def value(self, new_value):
self._value = new_value
@value.deleter
def value(self):
del self._x
import os
print(os.environ["WHATEVS"])
import os
print(os.path.exists("/some/path"))
import os
print(os.path.isfile("/some/path"))
print(os.path.isdir("/some/path"))
import os
print(os.path.getsize("/path/to/file"))
print("{:07d}".format(3))
# 0000003
__file__
NOTE: In the above example,
__file__
returns the path to the script in which that variable name is referenced, not the path of the script that was invoked. For example, consider the following situation. At the root of a project, I have a script calledfoo.py
that imports a function froma/b/c/bar.py
in the same project. The function ina/b/c/bar.py
references__file__
. Like this:# foo.py from a.b.c.bar import bar bar()
# a/b/c/bar.py def bar(): print(__file__)
python foo.py # /path/to/project/a/b/c/bar.py
import os
dir = (os.path.sep).join(__file__.split(os.path.sep)[:-1])
NOTE: See the note in the previous section regarding
__file__
.
import process
command = "ls -la"
subprocess.run(command, shell=True, executable="/bin/bash")
NOTE: According to this article: "If we pass a single string as a command to
subprocess.run()
, then the value of the argument must beTrue
for theshell
parameter. Otherwise, we must pass the command as a list of strings, andshell
must beFalse
."
import pickle
my_obj = { "hello": "world" }
# note the "wb" argument:
with open("my_file.pkl", "wb") as file:
pickle.dump(my_obj, file, protocol=5)
# note the "rb" argument:
with open("my_file.pkl", "rb") as file:
my_new_obj = pickle.load(file)
NOTE: There are serious security implications involved in this ☝️ process. The sklearn "Model persistence" page has a good summary of the different serialization tools.
NOTE: Also note that deserialization (at least with
pickle
) will fail if any of the relevant resources haven't yet been loaded. For example, if the object being deserialized has a property pointing to a function calledfoo
, thenfoo
must be loaded before deserialization can occur.