bpython -i & namespaces
I can't seem to find this answer anywhere.
Given the trivial example:
# myclass.py
class MyClass:
def __init__(self):
print 'test'
def main():
my_class_instance = MyClass()
if __name__ == '__main__':
main()
some_var = 'i exist! ... but I think I'm in global namespace?'
If I run bpython -i myclass.py, I execute the program & drop into the bpython environment. Whatever namespace I'm in - my_class_instance does not exist. However, some_var does exist - and so does the main function itself.
Is there anyway that I can pull any objects that exist in that main function into the namespace I'm in when I drop into that interactive prompt? Or is there someth开发者_JAVA百科ing else I should do?
my_class_instance
is in main
's namespace, so you can't see it outside of main
. Use a global instead:
my_class_instance = None
def main():
global my_class_instance
my_class_instance = MyClass()
Another trick I sometimes use when I want something back from running a main function is to return what I need at the end of main.
So, for example if I need an instance and some other variable from the main function in the top level one could do:
def main():
myclass = MyClass()
a = 4
return (my class, a)
if __name__ == '__main__':
ret = main()
If you now call your script with bpython -i scriptname you will have the variable 'ret' in the global namespace and ret[0] has your class instance, ret[1] has the number 4.
Using interactive bpython over python 2.7, __name__
is equal to __console__
. So your function main()
may be never called. A hack would be to write:
# myclass.py
class MyClass:
def __init__(self):
print 'test'
def main():
global my_class_instance
my_class_instance = MyClass()
if __name__ in ('__main__', '__console__'):
main()
精彩评论