##// END OF EJS Templates
Start converting user namespace machinery to use a module.
Thomas Kluyver -
Show More
@@ -372,7 +372,7 b' class InteractiveShell(SingletonConfigurable, Magic):'
372 _post_execute = Instance(dict)
372 _post_execute = Instance(dict)
373
373
374 def __init__(self, config=None, ipython_dir=None, profile_dir=None,
374 def __init__(self, config=None, ipython_dir=None, profile_dir=None,
375 user_ns=None, user_global_ns=None,
375 user_module=None, user_local_ns=None,
376 custom_exceptions=((), None)):
376 custom_exceptions=((), None)):
377
377
378 # This is where traits with a config_key argument are updated
378 # This is where traits with a config_key argument are updated
@@ -387,7 +387,7 b' class InteractiveShell(SingletonConfigurable, Magic):'
387 self.init_environment()
387 self.init_environment()
388
388
389 # Create namespaces (user_ns, user_global_ns, etc.)
389 # Create namespaces (user_ns, user_global_ns, etc.)
390 self.init_create_namespaces(user_ns, user_global_ns)
390 self.init_create_namespaces(user_module, user_local_ns)
391 # This has to be done after init_create_namespaces because it uses
391 # This has to be done after init_create_namespaces because it uses
392 # something in self.user_ns, but before init_sys_modules, which
392 # something in self.user_ns, but before init_sys_modules, which
393 # is the first thing to modify sys.
393 # is the first thing to modify sys.
@@ -860,7 +860,7 b' class InteractiveShell(SingletonConfigurable, Magic):'
860 # Things related to IPython's various namespaces
860 # Things related to IPython's various namespaces
861 #-------------------------------------------------------------------------
861 #-------------------------------------------------------------------------
862
862
863 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
863 def init_create_namespaces(self, user_module=None, user_local_ns=None):
864 # Create the namespace where the user will operate. user_ns is
864 # Create the namespace where the user will operate. user_ns is
865 # normally the only one used, and it is passed to the exec calls as
865 # normally the only one used, and it is passed to the exec calls as
866 # the locals argument. But we do carry a user_global_ns namespace
866 # the locals argument. But we do carry a user_global_ns namespace
@@ -897,19 +897,17 b' class InteractiveShell(SingletonConfigurable, Magic):'
897 # These routines return properly built dicts as needed by the rest of
897 # These routines return properly built dicts as needed by the rest of
898 # the code, and can also be used by extension writers to generate
898 # the code, and can also be used by extension writers to generate
899 # properly initialized namespaces.
899 # properly initialized namespaces.
900 user_ns, user_global_ns = self.make_user_namespaces(user_ns,
900 self.user_module = self.prepare_user_module(user_module)
901 user_global_ns)
902
901
903 # Assign namespaces
902 if user_local_ns is None:
904 # This is the namespace where all normal user variables live
903 user_local_ns = self.user_module.__dict__
905 self.user_ns = user_ns
904 self.user_local_ns = user_local_ns
906 self.user_global_ns = user_global_ns
907
905
908 # An auxiliary namespace that checks what parts of the user_ns were
906 # An auxiliary namespace that checks what parts of the user_ns were
909 # loaded at startup, so we can list later only variables defined in
907 # loaded at startup, so we can list later only variables defined in
910 # actual interactive use. Since it is always a subset of user_ns, it
908 # actual interactive use. Since it is always a subset of user_ns, it
911 # doesn't need to be separately tracked in the ns_table.
909 # doesn't need to be separately tracked in the ns_table.
912 self.user_ns_hidden = {}
910 self.user_ns_hidden = set()
913
911
914 # A namespace to keep track of internal data structures to prevent
912 # A namespace to keep track of internal data structures to prevent
915 # them from cluttering user-visible stuff. Will be updated later
913 # them from cluttering user-visible stuff. Will be updated later
@@ -946,8 +944,8 b' class InteractiveShell(SingletonConfigurable, Magic):'
946
944
947 # A table holding all the namespaces IPython deals with, so that
945 # A table holding all the namespaces IPython deals with, so that
948 # introspection facilities can search easily.
946 # introspection facilities can search easily.
949 self.ns_table = {'user':user_ns,
947 self.ns_table = {'user_global':user_module.__dict__,
950 'user_global':user_global_ns,
948 'user_local':user_local_ns,
951 'internal':self.internal_ns,
949 'internal':self.internal_ns,
952 'builtin':builtin_mod.__dict__
950 'builtin':builtin_mod.__dict__
953 }
951 }
@@ -958,66 +956,37 b' class InteractiveShell(SingletonConfigurable, Magic):'
958 # user_global_ns, can NOT be listed here, as clearing them blindly
956 # user_global_ns, can NOT be listed here, as clearing them blindly
959 # causes errors in object __del__ methods. Instead, the reset() method
957 # causes errors in object __del__ methods. Instead, the reset() method
960 # clears them manually and carefully.
958 # clears them manually and carefully.
961 self.ns_refs_table = [ self.user_ns_hidden,
959 self.ns_refs_table = [ self.internal_ns, self._main_ns_cache ]
962 self.internal_ns, self._main_ns_cache ]
960
963
961 @property
964 def make_user_namespaces(self, user_ns=None, user_global_ns=None):
962 def user_global_ns(self):
965 """Return a valid local and global user interactive namespaces.
963 return self.user_module.__dict__
966
967 This builds a dict with the minimal information needed to operate as a
968 valid IPython user namespace, which you can pass to the various
969 embedding classes in ipython. The default implementation returns the
970 same dict for both the locals and the globals to allow functions to
971 refer to variables in the namespace. Customized implementations can
972 return different dicts. The locals dictionary can actually be anything
973 following the basic mapping protocol of a dict, but the globals dict
974 must be a true dict, not even a subclass. It is recommended that any
975 custom object for the locals namespace synchronize with the globals
976 dict somehow.
977
964
978 Raises TypeError if the provided globals namespace is not a true dict.
965 def prepare_user_module(self, user_module=None):
966 """Prepares a module for use as the interactive __main__ module in
967 which user code is run.
979
968
980 Parameters
969 Parameters
981 ----------
970 ----------
982 user_ns : dict-like, optional
971 user_module : module, optional
983 The current user namespace. The items in this namespace should
972 The current user module in which IPython is being run. If None,
984 be included in the output. If None, an appropriate blank
973 a clean module will be created.
985 namespace should be created.
986 user_global_ns : dict, optional
987 The current user global namespace. The items in this namespace
988 should be included in the output. If None, an appropriate
989 blank namespace should be created.
990
974
991 Returns
975 Returns
992 -------
976 -------
993 A pair of dictionary-like object to be used as the local namespace
977 A module object.
994 of the interpreter and a dict to be used as the global namespace.
995 """
978 """
996
979 if user_module is None:
997
980 user_module = types.ModuleType("__main__",
981 doc="Automatically created module for IPython interactive environment")
982
998 # We must ensure that __builtin__ (without the final 's') is always
983 # We must ensure that __builtin__ (without the final 's') is always
999 # available and pointing to the __builtin__ *module*. For more details:
984 # available and pointing to the __builtin__ *module*. For more details:
1000 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
985 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
986 user_module.__dict__.setdefault('__builtin__',__builtin__)
987 user_module.__dict__.setdefault('__builtins__',__builtin__)
1001
988
1002 if user_ns is None:
989 return user_module
1003 # Set __name__ to __main__ to better match the behavior of the
1004 # normal interpreter.
1005 user_ns = {'__name__' :'__main__',
1006 py3compat.builtin_mod_name: builtin_mod,
1007 '__builtins__' : builtin_mod,
1008 }
1009 else:
1010 user_ns.setdefault('__name__','__main__')
1011 user_ns.setdefault(py3compat.builtin_mod_name,builtin_mod)
1012 user_ns.setdefault('__builtins__',builtin_mod)
1013
1014 if user_global_ns is None:
1015 user_global_ns = user_ns
1016 if type(user_global_ns) is not dict:
1017 raise TypeError("user_global_ns must be a true dict; got %r"
1018 % type(user_global_ns))
1019
1020 return user_ns, user_global_ns
1021
990
1022 def init_sys_modules(self):
991 def init_sys_modules(self):
1023 # We need to insert into sys.modules something that looks like a
992 # We need to insert into sys.modules something that looks like a
@@ -1036,13 +1005,8 b' class InteractiveShell(SingletonConfigurable, Magic):'
1036 # embedded in).
1005 # embedded in).
1037
1006
1038 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
1007 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
1039
1008 main_name = self.user_module.__name__
1040 try:
1009 sys.modules[main_name] = self.user_module
1041 main_name = self.user_ns['__name__']
1042 except KeyError:
1043 raise KeyError('user_ns dictionary MUST have a "__name__" key')
1044 else:
1045 sys.modules[main_name] = FakeModule(self.user_ns)
1046
1010
1047 def init_user_ns(self):
1011 def init_user_ns(self):
1048 """Initialize all user-visible namespaces to their minimum defaults.
1012 """Initialize all user-visible namespaces to their minimum defaults.
@@ -1073,8 +1037,8 b' class InteractiveShell(SingletonConfigurable, Magic):'
1073
1037
1074 # For more details:
1038 # For more details:
1075 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1039 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1076 ns = dict(__builtin__ = builtin_mod)
1040 ns = dict()
1077
1041
1078 # Put 'help' in the user namespace
1042 # Put 'help' in the user namespace
1079 try:
1043 try:
1080 from site import _Helper
1044 from site import _Helper
@@ -1109,7 +1073,7 b' class InteractiveShell(SingletonConfigurable, Magic):'
1109 # stuff, not our variables.
1073 # stuff, not our variables.
1110
1074
1111 # Finally, update the real user's namespace
1075 # Finally, update the real user's namespace
1112 self.user_ns.update(ns)
1076 self.user_local_ns.update(ns)
1113
1077
1114 def reset(self, new_session=True):
1078 def reset(self, new_session=True):
1115 """Clear all internal namespaces, and attempt to release references to
1079 """Clear all internal namespaces, and attempt to release references to
@@ -1260,13 +1224,13 b' class InteractiveShell(SingletonConfigurable, Magic):'
1260 self.user_ns.update(vdict)
1224 self.user_ns.update(vdict)
1261
1225
1262 # And configure interactive visibility
1226 # And configure interactive visibility
1263 config_ns = self.user_ns_hidden
1227 user_ns_hidden = self.user_ns_hidden
1264 if interactive:
1228 if interactive:
1265 for name, val in vdict.iteritems():
1229 for name in vdict:
1266 config_ns.pop(name, None)
1230 user_ns_hidden.discard(name)
1267 else:
1231 else:
1268 for name,val in vdict.iteritems():
1232 for name in vdict:
1269 config_ns[name] = val
1233 user_ns_hidden.add(name)
1270
1234
1271 def drop_by_id(self, variables):
1235 def drop_by_id(self, variables):
1272 """Remove a dict of variables from the user namespace, if they are the
1236 """Remove a dict of variables from the user namespace, if they are the
@@ -1284,7 +1248,7 b' class InteractiveShell(SingletonConfigurable, Magic):'
1284 for name, obj in variables.iteritems():
1248 for name, obj in variables.iteritems():
1285 if name in self.user_ns and self.user_ns[name] is obj:
1249 if name in self.user_ns and self.user_ns[name] is obj:
1286 del self.user_ns[name]
1250 del self.user_ns[name]
1287 self.user_ns_hidden.pop(name, None)
1251 self.user_ns_hidden.discard(name)
1288
1252
1289 #-------------------------------------------------------------------------
1253 #-------------------------------------------------------------------------
1290 # Things related to object introspection
1254 # Things related to object introspection
General Comments 0
You need to be logged in to leave comments. Login now