pyplugs
pyplugs copied to clipboard
Import functions from external file using pyplugs
Hi,
I want import extarnal function from my code to modify some characteristics of the code. I have the following structure inside of my code:
plugins/
__init__.py
And I want o import the function sum defined in external file inside of plugins, This is possible? I can import a completely external funciton to modify my code using pyplugs?
In other words my question is how I can register a external funcion using pyplugs? Can I use pyplugs.get to get an external funcion? Or How I can use pyplugs.register to register this external function?
Hi @AndresLaverdeMarin
You can do pyplugs.register(external_func)
to register an external function where you can't use the normal decorator syntax. For example:
>>> import pathlib
>>> pathlib.Path.cwd()
PosixPath('/home/gahjelle/Dropbox/programmering/realpython')
>>> import pyplugs
>>> pyplugs.register(pathlib.Path.cwd)
<bound method Path.cwd of <class 'pathlib.Path'>>
>>> pyplugs.call(package="", plugin="pathlib", func="cwd")
PosixPath('/home/gahjelle/Dropbox/programmering/realpython')
>>> pyplugs._plugins._PLUGINS
{'': {'pathlib': {'cwd': PluginInfo(package_name='', plugin_name='pathlib', func_name='cwd', func=<bound method Path.cwd of <class 'pathlib.Path'>>, description='Return a new path pointing to the current working directory\n (as returned by os.getcwd()).\n ', doc='', module_doc='', sort_value=0, label=None)}}}
Another example:
>>> from urllib import request
>>> request.urlopen("https://google.com/")
<http.client.HTTPResponse object at 0x7f7de62650d0>
>>> import pyplugs
>>> pyplugs.register(request.urlopen)
<function urlopen at 0x7f7dedb1c4c0>
>>> pyplugs.call(package="urllib", plugin="request", func="urlopen", url="https://google.com")
<http.client.HTTPResponse object at 0x7f7de6bf2490>
If you leave out func
, it will still pick the first function that has been registered inside the module (= plugin):
>>> pyplugs.call(package="urllib", plugin="request", url="https://google.com")
<http.client.HTTPResponse object at 0x7f7de6877280>
Does this work in your usecase?