dynamic execute a function by a string like 'module.function' [duplicate] - python

This question already has answers here:
Python function pointer
(8 answers)
Closed 9 years ago.
if I have a string like 'module.function', How can I execute function just by one step?
likesomefunction('os.error','args')

You can dynamically get the modules using sys.modules and then you can use getattr to get the attributes from the module, like this
import sys
func = "os.error"
module, function = func.split(".", 1)
getattr(sys.modules[module], function)()
sys.modules can give only the modules which are already loaded. So, if you want to load a module dynamically you can use __import__ function like this
For example,
module, function = "math.factorial".split(".", 1)
print getattr(__import__(module), function)(5)
Output
120

All you need to do is
from module import function
and you'll be able to call
function(x, y, z)
in your code.

Related

different python files sharing the same variables [duplicate]

This question already has answers here:
Using global variables between files?
(9 answers)
Closed 2 years ago.
I would like to know please, how can I define variables in a python file and share these variables with their values with multiple python files?
To do this, you can create a new module specifically for storing all the global variables your application might need. For this you can create a function that will initialize any of these globals with a default value, you only need to call this function once from your main class, then you can import the globals file from any other class and use those globals as needed.
You can create a python module
Create a py file inside that module define variables and import that module in the required places.

How do I get all the classes in a module? [duplicate]

This question already has answers here:
Python: get only classes defined in imported module with dir()?
(3 answers)
In Python, how do I get the list of classes defined within a particular file?
(4 answers)
Closed 2 years ago.
How do I get all the classes in a module? For example if a module has classes A, B and C, how do I get the names of all these classes through code?
Try this:
import importlib, inspect
inspect.getmembers(
importlib.import_module("your_module"),
inspect.isclass
)
this will give you what you are looking for.

How to programatically add or delete names in a module [duplicate]

This question already has answers here:
dynamically adding functions to a Python module
(2 answers)
Closed 2 years ago.
Suppose I create a module on the fly:
import imp
my_module = imp.new_module('my_module')
and I want to add n similar names/value to this module, something that would be equivalent to
my_module.a1 = None
my_module.a2 = None
my_module.a3 = None
...
How can I access a module namespace like a dictionary (or in a similar way) so that I can write something like
for i in range(n):
my_module.some_env_like_dict[f"a{i}"] = None
Also how can I remove these names in a similar way?
I understand that Python may not have a recommended or official way of doing this. Obviously this is not for any serious project.
I'm looking for a solution that is more elegant than using exec.
I think what you're doing is essentially correct, with just a few additions:
my_module = imp.new_module('my_module')
my_module.var1 = 123
This creates a module, and sets var1 to 123 within the module. You can access it as my_module.var1 just as you would for any other module.
To access the attributes from strings, you can do:
val = getattr(my_module, "var1")
setattr(my_module, "var1", val + 1)
This sets val to 123, then updates var1 in my_module with the value 124. You can also add new attributes to the module in this manner.

NLTK function from string variable isn't callable [duplicate]

This question already has answers here:
import module from string variable
(7 answers)
How can I import a module dynamically given its name as string?
(10 answers)
Closed 5 years ago.
I have a list of related function names which I want to iterate thru, calling the function held in the variable. But no matter how I try it, I get: "TypeError: 'TweetTokenizer' object is not callable"
Following the solution in Calling a function of a module from a string with the function's name in Python (of which it is suggested this question is a duplicate), finds the functions in the nltk module and assigns them. But my resulting "tok_alg" function is still failing as not callable. Any advice on why this is happening would be appreciated.
#!/usr/bin/env python
import nltk
import os
testTxt="I'll have a Bloomin' Onion."
Tokenizers = [ 'Tweet', 'MWE', 'TreebankWord' ]
for tokenizer in Tokenizers:
tokz = tokenizer + 'Tokenizer'
tok_alg = getattr(nltk, tokz)()
result = tok_alg(testTxt)
print(result)
Listing the functions does work, viz
for tokenizer in [ TweetTokenizer(), MWETokenizer() ]:
result = tokenizer.tokenize(testTxt)
But the suggested conversion of str variables via getattr() is not working for NLTK. While this is elegant and practical, I need the string variables for other purposes. Surely there is some way to vivify these into a function call. What am I missing?

Python __import__ is only giving me top level module [duplicate]

This question already has answers here:
How can I import a module dynamically given its name as string?
(10 answers)
Closed 9 years ago.
I'm doing
module = __import__("client.elements.gui.button", globals(), locals(), [], 0)
But it's only returning client.
What is my problem?
That's what __import__ does.
When the name variable is of the form package.module, normally, the top-level package (the name up till the first dot) is returned, not the module named by name.
You're not really supposed to use __import__; if you want to import a module dynamically, use importlib.import_module.
Accepted answer is correct, but if you read on in the docs you'll find that this can be gotten around with an admittedly unsettling "hack" by using __import__ like so:
module = __import__('client.elements.gui.button', fromlist=[''])
It doesn't really matter what you pass in for fromlist so long as it's a non-empty list. This signals to the default __import__ implementation that you want to do a from x.y.z import foo style import, and it will return the the module you're after.
As stated you should use importlib instead, but this is still a workaround if you need to support Python versions < 2.7.
It only obtains the top level, but you can also work around this like so:
module_name = 'some.module.import.class'
module = __import__(module_name)
for n in module_name.split('.')[1:]:
module = getattr(module, n)
# module is now equal to what would normally
# have been retrieved where you to properly import the file

Categories

Resources