Calling a function within a function with python - python

so here is my problem, I am trying to create a function in Python that refers to another function
Here is my code:
def movies_creation():
for director in directors:
for i in range((int(director.age)-20)/random.randint(1,5)):
movie = MOVIE([], random.randint(1960, 2015),
random.choice(movie_genre), 0, [], director, 0, 0, 0)
movie_title_type = random.randint(1,40)
if movie_title_type == 1:
title_colors()
director.filmography.append(movie)
def title_colors():
movie.name.append(random.choice(title_colors))
Now when I try to run this code I get this error message:
Traceback (most recent call last):
File "C:\Users\Patrick\Pictures\Python\TS\gui.py", line 7, in
movies_creation()
File "C:\Users\Patrick\Pictures\Python\TS\Movies.py", line 401, in movies_creation
title_colors()
File "C:\Users\Patrick\Pictures\Python\TS\Movies.py", line 343, in title_colors
movie.name.append(random.choice(title_colors)) NameError: global name 'movie' is not defined
Not sure what I am doing wrong...

Problem in your code is that you should pass the movie variable to the method title_colors:
title_colors(movie)
def title_colors(m):
m.name.append(random.choice(title_colors))

Thanks for your help, my problem was my function had the same name than a list in my program. changed the name and everything works fine now

Related

Trying to make a one hour loop in python

from notifypy import Notify
import schedule
def remember_water():
notification = Notify()
notification.title = "XXX"
notification.message = "XXX"
notification.send()
schedule.every().hour.do(remember_water())
while True:
schedule.run_pending()
time.sleep(1)
Tried to make a notification to drink water every hour... getting a type error when execute, maybe there are some other modules that are better.
Did´nt get in touch with these modules ever, pls help :)
Running your code produces:
Traceback (most recent call last):
File "/home/lars/tmp/python/drink.py", line 11, in <module>
schedule.every().hour.do(remember_water())
File "/home/lars/.local/share/virtualenvs/lars-rUjSNCQn/lib/python3.10/site-packages/schedule/__init__.py", line 625, in do
self.job_func = functools.partial(job_func, *args, **kwargs)
TypeError: the first argument must be callable
Your problem is here:
schedule.every().hour.do(remember_water())
The argument to the .do method must be a callable (like a function), but you are calling your function here and passing the result. You want to pass the function itself:
schedule.every().hour.do(remember_water)

My question is about the functionality of the 'eval' function when this is included in a function of an imported module

I have created a simple function for reporting current values of variables in some engineering scripts, by passing the variable name in an eval() function. The argument is passed as string then the eval() reads it and reports back the value with some additional info. The function works properly in a single script. However when i am importing the same function from a module i get back an error saying that the variable has is not defined.
I have trying setting it up as a global variable but still get the same problem
def report(name,units = '-',comment ='NC'):
if type(eval(name)) == str:
print('{0:<12}= {1:^10} {2:^5} {3}'.format(name,eval(name),units,comment))
else:
print('{0:<12}= {1:8.3f} {2:^5} {3}'.format(name,eval(name),units,comment))
While trying to use the function from the imported module i get the following
>>>from reporting import*
>>> from shapes import*
>>> Iyy = rec_Iyy(40,60)
>>> report('Iyy')
Traceback (most recent call last):
File "<pyshell>", line 1, in <module>
File "C:\Users\vousvoukisi\OneDrive\11.Python\03_myScripts\design_mod\reporting.py", line 8, in report
if type(eval(name)) == str:
File "<string>", line 1, in <module>
NameError: name 'Iyy' is not defined
## while i would expect the outcome to be :
>>> %Run reporting.py
Iyy = 720000.000 - NC

Importing Dictionary Fails

I'm trying to get too clever for my own good and have split out the data in my python script into three files. I want to bring the two reference files dictionaries into the main script, but can't get them to load no matter what I do. I'm sure its something simple, but I'm at my wits end. All the files are in the same folder.
Swordguy.py
stats = {
"Name":"Swordguy",
"Hp":20,
"Mp":20,
"St":20,
"Fight":8,
"Magic":2,
"Sneak":4,
"Athletics":2,
"Animal":0,
"Traps":-2
}
Room.py
info = {
"Name": "Rat Warren",
"Fight": 0,
"Magic": 2,
"Sneak": -2,
"Athletics": 0,
"Animal": 2
}
Testing.py
from Swordguy import stats
from Room import info
charname = stats["Name"]
roomname = info["Name"]
print(stats["Name"]+" arrives in the room "+info["Name"])
End result should read Swordguy arrived in the room Rat Warren but I'm getting the error message
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: cannot import name 'stats' from 'Swordguy'
I'm running the code in Visual Studio Core. I'm just using the inbuilt run command shift+enter
Edit 2: Looks like something is going on in how I'm running the code. Thanks everyone, glad its not just me losing my marbles.
You can make a function in Swordguy.py like this
def get_stats():
return stats
And do the same for Room.py
Now in testing.py import that function and call it like
from Swordguy import get_stats
from Room import get_info
stats = get_stats()
info = get_info()
charname = stats["Name"]
roomname = info["Name"]

NameError: name 'myconf' is not defined

I am working on web2py image blog.
I am unable to understand these errors:
Internal error
Ticket issued: images/127.0.0.1.2016-11-22.16-44-39.95144250-6a2e-4648-83f9-aa55873e6ae8
Error ticket for "images"
Ticket ID
127.0.0.1.2016-11-22.16-44-39.95144250-6a2e-4648-83f9-aa55873e6ae8
type 'exceptions.NameError'> name 'myconf' is not defined
Version
web2py™ Version 2.14.6-stable+timestamp.2016.05.10.00.21.47
Python Python 2.7.12: /usr/bin/python (prefix: /usr)
Traceback (most recent call last):
File "/home/sonu/Software/web2py /gluon/restricted.py", line 227, in restricted
exec ccode in environment
File "/home/sonu/Software/web2py /applications/images/models/menu.py", line 17, in
response.meta.author = myconf.get('app.author')
NameError: name 'myconf' is not defined
This post seems to be discussed here.
resolved/work around
I fixed this very same problem as follows:
I removed models/menu.py, and then the problem appears to be solved.
=> Remeber delete the models/menu.py

Python : NameError: global name 'GetText' is not defined

I have been stuck with this error for a couple of hours now. Not sure what is wrong. Below is the piece of code
NameError: global name 'GetText' is not defined
class BaseScreen(object):
def GetTextFromScreen(self, x, y, a, b, noofrows = 0):
count = 0
message = ""
while (count < noofrows):
line = Region(self.screen.x + x, self.screen.y + y + (count * 20), a, b)
message = message + "\n" + line.text()
count += 1
return message
class HomeScreen(BaseScreen):
def GetSearchResults(self):
if self.screen.exists("Noitemsfound.png"):
return 'No Items Found'
else:
return self.GetTextFromScreen(36, 274, 680, 20, 16)
class HomeTests(unittest.TestCase):
def test_001S(self):
Home = HomeScreen()
Home.ResetSearchCriteria()
Home.Search("0009", "Key")
self.assertTrue("0009" in Home.GetSearchResults(), "Key was not returned")
Basescreen class has all the reusable methods applicable across different screens.
Homescreen inherits Basescreen.
In HomeTests test case class, the last step is to Home.GetSearchResults() which in turn calls a base class method and the error.
Note:
I have another screenclass and testcaseclass doing the same which works without issues.
I have checked all the importing statements and is ok
'GetText' in the error message is the name of method initially after which i changed it to GetTextFromScreen
Error message is still pointing to a line 88 in code which is not there any more. Module import/reloading issue?
Try clearing out your *.pyc files (or __pycache__ if using 3+).
You asked:
Error message is still pointing to a line 88 in code which is not there any more. Module import/reloading issue?
Yes. The traceback (error messages) will show the current (newest saved) file, even if you haven't run it yet. You must reload/reimport to get the new file.
The discrepancy comes from the fact that traceback printouts read from the script file (scriptname.py) saved on your drive. However, the program is run either from the module saved in memory, or sometimes from the .pyc file. If you fix an error by changing your script, and save it to your drive, then the same error will still occur if you don't reload it.
If you're running interactively for testing, you can use the reload function:
>>> import mymodule
>>> mymodule.somefunction()
Traceback (most recent call last):
File "mymodule.py", line 3, in somefunction
Here is a broken line
OhNoError: Problem with your file
Now, you fix the error and save mymodule.py, return to your interactive session, but you still get the error, but the traceback shows the fixed line
>>> mymodule.somefunction()
Traceback (most recent call last):
File "mymodule.py", line 3, in somefunction
Here is the fixed line
OhNoError: Problem with your file
So you have to reload the module:
>>> reload(mymodule)
<module 'mymodule' from '/path/to/mymodule.py'>
>>> mymodule.somefunction()
Success!

Categories

Resources