简体   繁体   中英

IPython Configurable with custom class

I'm trying to use the IPython configuration system to provide configuration parameters for my own class. I tried a simple test.

from IPython.config.configurable import Configurable
from IPython.utils.traitlets import Int, Unicode, Bool

class MyConfigTest(Configurable):
    user_name = Unicode(u'Fred', config=True)

    def __init__(self, config=None):
        super(MyConfigTest, self).__init__(config=config)

    def display(self):
        print 'my name is ' + self.user_name

And then put this in my config file:

c.MyConfigTest.user_name = 'John'

When I run IPython --debug I can see that my config variable is being read properly:

[TerminalIPythonApp] Config changed:
[TerminalIPythonApp] {'MyConfigTest': {'user_name': 'John'}, 'TerminalIPythonApp
': {'log_level': 10}}

But when I instantiate MyConfigTest in my code it still has the default value:

In [1]: x = MyConfigTest()

In [2]: x
Out[2]: <__main__.MyConfigTest at 0x2e1dc50>

In [3]: x.display()
my name is Fred

Am I reading in the variable incorrectly? I read through some of the IPython source and I can't see anything obvious.

The config system creates a config object, which is passed in when classes are instantiated, to configure them. If you want to use it within IPython, you could do it like this:

x = MyConfigTest(config=get_ipython().config)

We don't really intend this system for configuring user objects inside IPython, though. It's possible, but not a use case that the config system is designed for. It is designed for configuring classes in IPython extensions, and to be sufficiently general that you can use it for entirely separate applications (by subclassing IPython.config.application.Application ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM