Skip to content

Instantly share code, notes, and snippets.

@jbcrail
Last active November 14, 2017 21:51
Show Gist options
  • Save jbcrail/3c76ea97f2e99ae16272ccc265f6d525 to your computer and use it in GitHub Desktop.
Save jbcrail/3c76ea97f2e99ae16272ccc265f6d525 to your computer and use it in GitHub Desktop.
Test case for runpy
from __future__ import print_function
class App(object):
def __init__(self, a='', b=0, c=False):
print(" ", a, b, c)
class Foo(App):
def __init__(self):
super(Foo, self).__init__(a='bar', b=80, c=True)
from __future__ import print_function
import importlib
import inspect
import sys
print("loading as module...")
mod = importlib.import_module('foo')
for _, cls in inspect.getmembers(mod, inspect.isclass):
if issubclass(cls, object) and cls.__module__ == 'foo':
print(" ", cls, cls())
try:
import runpy
print("loading as path via runpy...")
globals = runpy.run_path('foo.py')
for _, obj in globals.items():
if inspect.isclass(obj) and issubclass(obj, object) and obj.__module__ == '<run_path>':
print(" ", obj, obj())
except Exception as e:
import imp
import os.path
print("failed loading via runpy:", e)
print("loading as path via imp...")
module = os.path.splitext('foo.py')[0]
mod = imp.load_source(module, 'foo.py')
for name in mod.__dict__:
obj = getattr(mod, name)
if inspect.isclass(obj) and issubclass(obj, object) and obj.__module__ == module:
print(" ", obj, obj())
# Python 2.7 (python test_foo.py)
loading as module...
0 False
<class 'foo.App'> <foo.App object at 0x102b63e50>
bar 80 True
<class 'foo.Foo'> <foo.Foo object at 0x102b63e50>
loading as path via runpy...
0 False
<class '<run_path>.App'> <<run_path>.App object at 0x102b72f50>
failed loading via runpy: super() argument 1 must be type, not None
loading as path via imp...
0 False
<class 'foo.App'> <foo.App object at 0x102b72ed0>
bar 80 True
<class 'foo.Foo'> <foo.Foo object at 0x102b72ed0>
# Python 3.6 (python test_foo.py)
loading as module...
0 False
<class 'foo.App'> <foo.App object at 0x10b51ff98>
bar 80 True
<class 'foo.Foo'> <foo.Foo object at 0x10b51ff98>
loading as path via runpy...
0 False
<class '<run_path>.App'> <<run_path>.App object at 0x10b5a9cc0>
bar 80 True
<class '<run_path>.Foo'> <<run_path>.Foo object at 0x10b5a9cc0>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment