how to assign variable to module name in python function - python

I have a set of modules, and I want to be able to call one of them within a function based on an argument given to that function. I tried this, but it doesn't work:
from my.set import modules
def get_modules(sub_mod):
variable = sub_mod
mod_object = modules.variable
function(mod_object)
I get:
AttributeError: 'module' object has no attribute 'variable'
It's not taking the argument I give it, which would be the name of a module that exists under my.set.modules. so if I called the function get_modules(name_of_mod_under_modules), I would like the line modules.variable to be "modules.name_of_mod_under_modules" which I could then have as an object passed to mod_object.

In your current code, you're looking for modules.variable which doesn't exist, hence the error! That's not how you get an attribute of an object.
To achieve what you wanted, use the getattr function.
mod_object = getattr(modules, variable)

Related

object is not callable but I do not know how to divide the module into each other

import mains
print(mains.hi())
import parsogv2
print(parsogv2.gets())
priliv = mains()/parsogv2()
I have this trouble 'module' object is not callable. I want to split the values I get in modules How to do it better ? Combine them into one module or can I do as I wanted in the code ?
If what you've been trying to do is divide the return values of mains.hi() and parsogv2.gets(), then what you should be doing is:
priliv = mains.hi()/parsogv2.gets()
The error you've been receiving, informing you that a module is not callable, is a result of your attempt to call the actual modules (mains and parsogv2) instead of the functions they contain (mains.hi and parsogv2.gets), which I assume is what you were going for.

Calling class methods dinamically using Python [duplicate]

I would like to call an object method dynamically.
The variable "MethodWanted" contains the method I want to execute, the variable "ObjectToApply" contains the object.
My code so far is:
MethodWanted=".children()"
print eval(str(ObjectToApply)+MethodWanted)
But I get the following error:
exception executing script
File "<string>", line 1
<pos 164243664 childIndex: 6 lvl: 5>.children()
^
SyntaxError: invalid syntax
I also tried without str() wrapping the object, but then I get a "cant use + with str and object types" error.
When not dynamically, I can just execute this code to get the desired result:
ObjectToApply.children()
How to do that dynamically?
Methods are just attributes, so use getattr() to retrieve one dynamically:
MethodWanted = 'children'
getattr(ObjectToApply, MethodWanted)()
Note that the method name is children, not .children(). Don't confuse syntax with the name here. getattr() returns just the method object, you still need to call it (jusing ()).

How to use getattr and string for calling class?

somelist=[1,2,3,4,5]
class HI:
a="QWERTY"
def test(wannacall):
test1="testing"+str(wannacall)
print(getattr(test1,"a")) #<- this part makes error 'str' object has no attribute 'a'.
testing1=HI()
test(somelist[0])
I know why this error happens, but I can't solve this.
(Sorry for my bad English.)
Edit: I know why that error happens, but I want to make code shorter than this:
somelist=[1,2,3,4,5]
class HI:
a="QWERTY"
def test(wannacall):
if wannacall==1:
print(getattr(testing1,"a"))
test1="testing"+str(wannacall)
testing1=HI()
test(somelist[0])
because the code will be longer if there are more classes. (ex: testing2, testing3, testing4).
+++ I solved this with eval() — my friend helped me.
print(getattr(eval(test1),"a"))
Your problem comes from not using getattr correctly.
The getattr() method takes multiple parameters:
1.object - object whose named attribute's value is to be returned
For example:
HI= HI() #declare the class
getattr(HI,.....)
2.name - a string that contains the attribute's name
For example:
getattr(HI, "a", ...)
3.default (Optional) - value that is returned when the named attribute is not found
For example:
getattr(HI, "a", "QRDefult")
What you are doing in your way is your using a string as the first parameter instead of an object. Just because your string has the same name as your object doesn't mean its an object.
you can do this instead
somelist=[1,2,3,4,5]
class HI:
b="QWERTY"
def test(object, wannacall):
test1="testing" + str(wannacall)
print(test1)
print(getattr(object,"b")) #<- this part makes error 'str' object has no attribute 'a'.
object=HI()
test(object,somelist[0])

When we import a module do we have a method in Python?

So the question is basically:
I have a module called Fibo that has, for example, a function called fibonacci() that calculates a Fibonacci sequence. Since I want to use this in my program, I have to do this:
import Fibo
Fibo.fibonacci()
But this last line isn't an object with a method called fibonacci or actually it is?
Everything in Python is an object. If you're importing an object from a module, you will have the object in your current/actual module (i.e. program). You can create different namespaces and make your code more organized by using different files for your Python code. That's the advantage of using other modules and importing from it.
According to the Python documentation, it is better to simply avoid calling fibonacci a method and say that it is an attribute of an object, see:
method
A function which is defined inside a class body. [...]
attribute
A value associated with an object which is referenced by name using dotted expressions. For example, if an object o has an attribute a it would be referenced as o.a.
In the official documentation you can find the answer.
It boils down to this:
"When a module is first imported, Python searches for the module and if found, it creates a module object 1, initializing it."
So basically, yes, Fibo is an object.

How to use a dictionary that's been declared and filled in another file in Python?

I am having trouble trying to import a dictionary object that I have declared and filled with key,value pairs in another Python file.
A bit of background -- I am working with accessing the Reddit API and then filling a dictionary with subreddit names and a score I have given them, based off of Reddit comments that have been retrieved. My main goal with importing the dictionary is in order to find a way to work with said dictionary of data, to mess around with, without having to make repeated calls to the API and having to wait to keep refilling the dictionary each time I want to test if it runs.
At the moment, I have looked around the internet and other questions on StackOverflow about importing just a dictionary object from another file and class and I keep getting the same error where it says that the 'module' object has no attribute. Please see my example below:
from subreddit_score import main
# the dictionary obj that I wish to use in subreddit_score.py is called top_five
d = subreddit_score.top_five
I'm unsure as to why this is, so if someone would be able to help me I would greatly appreciate it.
Also: if there is a better way to do this, I would also appreciate any input. But I am mainly just asking for a way to import a dictionary variable.
Thanks!
EDIT:
Traceback error:
Traceback (most recent call last):
File "tester.py", line 8, in <module>
d = subreddit_score.top_five
AttributeError: 'module' object has no attribute 'top_five'
subreddit_score.py
def main():
# fetchRedditData() returns a dictionary
top_five = fetchRedditData()
from subreddit_score import main
# the dictionary obj that I wish to use in subreddit_score.py is called top_five
d = subreddit_score.top_five
You're getting the "'module' object has no attribute" error because you are trying to get the value of top_five but it's in a function, not a member of the module which could be accessed from anywhere.
To fix this, you could either change the main() function you have into a getter type object (also, you probably should name this function something other than main)
def main():
# fetchRedditData() returns a dictionary
top_five = fetchRedditData
return top_five
Or if you want to access the dictionary as a member object, you could just make it global within the file, but I would recommend against this as it is poor design,
top_five is local to the function main in your subreddit_score module. Because it's not in the module scope, you cannot access it as though it was - in a similar way, you won't be able to access it from other functions in the same module.
The quickest fix to this, would be to just make it a global in the module, although this is likely not the best design:
top_five = None
def main():
global top_five
top_five = fetchRedditData()
Now you can access top_five from another module that imports this module, but you're temporally coupled to having run main first.

Categories