Skip to content

Commit 675c047

Browse files
committedDec 21, 2017
wrapping in try/finally
1 parent 787ab24 commit 675c047

File tree

1 file changed

+34
-33
lines changed

1 file changed

+34
-33
lines changed
 

‎src/cs50/__init__.py

Lines changed: 34 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -1,47 +1,48 @@
11
import os
22
import sys
33

4-
# Save student's sys.path
5-
path = sys.path[:]
6-
7-
# In case student has files that shadow packages
8-
sys.path = [p for p in sys.path if p not in ("", os.getcwd())]
9-
10-
# Import cs50_*
11-
from .cs50 import eprint, get_char, get_float, get_int, get_string
124
try:
13-
from .cs50 import get_long
14-
except:
15-
pass
165

17-
# Monkey patches
18-
from . import flask
6+
# Save student's sys.path
7+
path = sys.path[:]
8+
9+
# In case student has files that shadow packages
10+
sys.path = [p for p in sys.path if p not in ("", os.getcwd())]
1911

12+
# Import cs50_*
13+
from .cs50 import eprint, get_char, get_float, get_int, get_string
14+
try:
15+
from .cs50 import get_long
16+
except:
17+
pass
2018

21-
class CustomImporter(object):
22-
"""
23-
Import cs50.SQL lazily so that rest of library can be used without SQLAlchemy installed.
19+
# Replace flask's logger
20+
from . import flask
2421

25-
https://docs.python.org/3/library/imp.html
26-
http://xion.org.pl/2012/05/06/hacking-python-imports/
27-
http://dangerontheranger.blogspot.com/2012/07/how-to-use-sysmetapath-with-python.html
28-
"""
22+
class CustomImporter(object):
23+
"""
24+
Import cs50.SQL lazily so that rest of library can be used without SQLAlchemy installed.
2925
30-
def find_module(self, fullname, path=None):
31-
if fullname == "cs50.SQL":
32-
return self
33-
return None
26+
https://docs.python.org/3/library/imp.html
27+
http://xion.org.pl/2012/05/06/hacking-python-imports/
28+
http://dangerontheranger.blogspot.com/2012/07/how-to-use-sysmetapath-with-python.html
29+
"""
3430

35-
def load_module(self, name):
36-
if name in sys.modules:
37-
return sys.modules[name]
38-
from .sql import SQL
39-
sys.modules[name] = SQL
40-
return SQL
31+
def find_module(self, fullname, path=None):
32+
if fullname == "cs50.SQL":
33+
return self
34+
return None
4135

36+
def load_module(self, name):
37+
if name in sys.modules:
38+
return sys.modules[name]
39+
from .sql import SQL
40+
sys.modules[name] = SQL
41+
return SQL
4242

43-
sys.meta_path.append(CustomImporter())
43+
sys.meta_path.append(CustomImporter())
4444

45+
finally:
4546

46-
# Restore student's sys.path
47-
sys.path = path
47+
# Restore student's sys.path (just in case library raised an exception that caller caught)
48+
sys.path = path

0 commit comments

Comments
 (0)