ValuError using import function in class - python

I'm sure there's a simple explanation for this (beyond just that I'm new to Python), but let's say I have two file in the same directory. One is this little script in a file named lexicon.py that checks user input:
def string_checker3(action):
try:
check = isinstance(action, basestring)
if check:
return True
else:
raise ValueError
except ValueError:
print "We need a string here!"
return None
def Chipcar_testgreeting(action):
action_split = action.split()
for i in action_split:
strcheck = string_checker3(action)
if strcheck == None:
StartGame
else:
pass
The other script, my main script, is called newGame.py and has a class like this, within which I would like to call the Chipcar_testgreeting(action) function.
from lexicon import *
class ChipCar(Scene):
def enter(self):
print "What's up mothafucka! Get in the Bran Muffin car!"
action = raw_input("> ")
user_test = lexicon.Chipcar_testgreeting(action)
user_test
if(action == "shut up chip" or action == "oh no, it's chip"):
print "forget you!"
print action
return next_scene('Your_death')
#return 'Death'
elif(action == "hi chip" or action == "hello chip"):
print "What's up?!?! Let's go to O&A..."
return next_scene('Chip_in_studio')
else:
print "what's wrong with ya are ya stupid or sumptin? Let's go to my mudda's house, I think Lamar's there..."
return next_scene('Chip_mom_house')
FirstScene = ChipCar()
StartGame = FirstScene.enter()
However, I get this error now:
user_test = lexicon.Chipcar_testgreeting(action)
NameError: global name 'lexicon' is not defined
What am I doing wrong?

As you wrote from lexicon import *, all the importable names from that module are available to you directly (in other words, you don't need lexicon. anymore).
If you write import lexicon, now you have only imported the lexicon name into your module, and you need to use it and the scope-resolution operator (that's the .) to get to the other names of objects inside that module. In this case, you can use lexicon.Chipcar_testgreeting(action).
So, either replace from lexicon import * with import lexicon, or change lexicon.Chipcar_testgreeting(action) to Chipchar_testgreeting(action).
The recommended option is to use import lexicon.
Once you sort that out, you need to resolve another major issue which is this:
if strcheck == None:
StartGame
else:
pass
Not sure what do you expect StartGame to do here, since there is nothing with this name in the lexicon.py module.

Related

How can I increase code readability in python for this?

I am running my script in Flask and to catch and print the errors on the server I have made functions that either return None if succeeded else return an error message.
The problem is I have many functions which runs one after another and uses global variable from earlier function, this makes the code unorganized. What can I do?
App.py
from flask import Flask
from main import *
app = Flask(__name__)
#app.route('/')
def main():
input = request.args.get('input')
first_response = function1(input)
if first_response is None:
second_response = function2() # no input from hereon
if second_response is None:
third_response = function3() # functions are imported from main.py
if third_response is None:
...
if ...
else ...
else:
return third_response
else:
return second_response
else:
return first_response
main.py
def function1(input):
global new_variable1
if input is valid:
new_variable1 = round(input,2)
else:
return "the value is not integer"
def function2():
global new_variable2
if new_variable1 > 8:
new_variable2 = new_variable1 / 8
else:
return "the division is not working, value is 0"
def function3():
...
This is just a demo of what's going on. The last function will return a value either side. So if everything goes right I would be able to see the right output as well as I will see error on any given function.
The code works fine, but I need better alternative to do this.
Thanks!
Ah...you have (correctly) determined that you have two things to do:
Process your data, and
Deal with errors.
So let's process the data replacing global with parameteters (and come back to the error handling in a bit). You want to do something like this.
main.py
def function1(some_number):
if some_number is valid:
return round(some_number, 2)
def function2(a_rounded_number):
if a_rounded_number > 8:
return a_rounded_number / 8
So each function should return the results of its work. Then the calling routine can just send the results of each function to the next function, like this:
app.py
# [code snipped]
result1 = function1(the_input_value)
result2 = function2(result1)
result3 = function3(result2)
But...how do we deal with unexpected or error conditions? We use exceptions, like this:
main.py
def function1(some_number):
if some_number is valid:
return round(some_number, 2)
else:
raise ValueError("some_number was not valid")
and then in the calling routine
app.py
try:
result1 = function1(some_input_value)
except (ValueError as some_exception):
return str(some_exception)

Multiple Try/Except for Validate Config-File

Thats my first question on Stackoverflow and im a totally Python beginner.
I want to write, to get firm with python, a small Backup-Programm, the main part is done, but now i want to make it a bit "portable" and use a Config file, which i want to Validate.
My class "getBackupOptions" should be give Back a validate dict which should be enriched with "GlobalOptions" and "BackupOption" so that i finally get an fully "BackupOption" dict when i call "getBackupOptions.BackupOptions".
My Question now is, (in this Example is it easy, because its only the Function which check if the Path should be Recursive searched or not) how to simplify my Code?
For each (possible) Error i must write a new "TryExcept" Block - Can i Simplify it?
Maybe is there another way to Validate Config Files/Arrays?
class getBackupOptions:
def __init__(self,BackupOption,GlobalOptions):
self.BackupOption = BackupOption
self.GlobalOptions = GlobalOptions
self.getRecusive()
def getRecusive(self):
try:
if self.BackupOption['recursive'] != None:
pass
else:
raise KeyError
except KeyError:
try:
if self.GlobalOptions['recursive'] != None:
self.BackupOption['recursive'] = self.GlobalOptions['recursive']
else:
raise KeyError
except KeyError:
print('Recusive in: ' + str(self.BackupOption) + ' and Global is not set!')
exit()
Actually i only catch an KeyError, but what if the the Key is there but there is something else than "True" or "False"?
Thanks a lot for you help!
You may try this
class getBackupOptions:
def __init__(self,BackupOption,GlobalOptions):
self.BackupOption = BackupOption
self.GlobalOptions = GlobalOptions
self.getRecusive()
def getRecusive(self):
if self.BackupOption.get('recursive') == 'True' and self.GlobalOptions.get('recursive') == 'True':
self.BackupOption['recursive'] = self.GlobalOptions['recursive']
else:
print('Recusive in: ' + str(self.BackupOption) + ' and Global is not set!')
exit()
Here get method is used, therefore KeyError will not be faced.
If any text other than True comes in the field it will be considered as False.

Python: Have an action happen within every single function of a python file

Sorry the title isn't very clear but it is kind of hard to explain. So I am wondering how you can have a certain action happen within every single function of a python file. I want a user to type 'paper' inside any function in the entire python file and I cannot figure out how to do it. Here is an example:
def a():
raw_input()
print "Test"
def b():
raw_input()
print "Test 2"
How can I have it setup so a user can type 'paper' in these two functions (realistically more than 30+) and then it would print the statement "you have a paper"
Thank you so much for the help!
If you have something you want to apply to every function, you should use a decorator. I'm not exactly sure what you're trying to accomplish, but this should demonstrate:
>>> def youhaveapaper(function):
def wrapper(*args):
response = input('whatchu got?\n>>> ')
if response == 'paper':
print('you have a paper')
return function(*args)
import functools
functools.update_wrapper(wrapper, function)
return wrapper
>>> #youhaveapaper
def somefunction(x):
"""return the square of x"""
return x**2
>>> y = somefunction(5)
whatchu got?
>>> paper
you have a paper
>>> y
25
As you can see, somefunction did not need to be changed, it just needed #youhaveapaper placed before the definition.
Please see the good comments and questions above. Do you mean this:
#!/usr/bin/python
def paper(prompt):
response = raw_input(prompt+' ')
print('you have a {}'.format(response))
def a():
paper('Test')
def b():
paper('Test2')
a()
b()

exposing the inner methods of a class, and using them

Let's say I have a class like so:
class Shell:
def cat(self, file):
try:
with open(file, 'r') as f:
print f.read()
except IOError:
raise IOError('invalid file location: {}'.format(f))
def echo(self, message):
print message
def ls(self, path):
print os.listdir(path)
In a javascript context, you might be able to do something like "Class"[method_name](), depending on how things were structured. I am looking for something similar in python to make this a "simulated operating system". EG:
import os
def runShell(user_name):
user_input = None
shell = Shell()
while(user_input != 'exit' or user_input != 'quit'):
user_input = raw_input('$'+ user_name + ': ')
...
now, the idea is they can type in something like this...
$crow: cat ../my_text
... and behind the scenes, we get this:
shell.cat('../my_text')
Similarly, I would like to be able to print all method definitions that exist within that class when they type help. EG:
$crow: help\n
> cat (file)
> echo (message)
> ls (path)
is such a thing achievable in python?
You can use the built-in function vars to expose all the members of an object. That's maybe the simplest way to list those for your users. If you're only planning to print to stdout, you could also just call help(shell), which will print your class members along with docstrings and so on. help is really only intended for the interactive interpreter, though, so you'd likely be better off writing your own help-outputter using vars and the __doc__ attribute that's magically added to objects with docstrings. For example:
class Shell(object):
def m(self):
'''Docstring of C#m.'''
return 1
def t(self, a):
'''Docstring of C#t'''
return 2
for name, obj in dict(vars(Shell)).items():
if not name.startswith('__'): #filter builtins
print(name, '::', obj.__doc__)
To pick out and execute a particular method of your object, you can use getattr, which grabs an attribute (if it exists) from an object, by name. For example, to select and run a simple function with no arguments:
fname = raw_input()
if hasattr(shell, fname):
func = getattr(shell, fname)
result = func()
else:
print('That function is not defined.')
Of course you could first tokenize the user input to pass arguments to your function as needed, like for your cat example:
user_input = raw_input().split() # tokenize
fname, *args = user_input #This use of *args syntax is not available prior to Py3
if hasattr(shell, fname):
func = getattr(shell, fname)
result = func(*args) #The *args syntax here is available back to at least 2.6
else:
print('That function is not defined.')

"Son" function cant see "Father" function locals

Hi im doing a udacity course on testing and I dont understand why im getting this problem with globals.
The thing is there is some implementation of queue I want to test. To do so I wrapp the methods with the post conditions [empty, full,enqueue,dequeue] using asserts and then proceed to do a random test on the structure with the wrapped functions to automate the testing.
For the assertions I need to keep track of the max items (size) of the queue and the actual items (elts) so i defined them as locals in function test().
Inside test() i define the wrapers and in the wrappers i use size and elts.
The thing i dont understand is if i make elts global inside the wrapper definition, then i got a NameError global name 'elts' is not defined at the wrapper But if i dont declare it as global in the wrapper then i get the UnboundLocalError of accessing elts before assigning a value to it.
I dont understand why a "Son" function declared in the body of a "Father" function cant see a local variable of the father and use it.
Here is the code
from queue_test import *
import random
import sys
def test():
# Globals
iters=100
max_int=sys.maxint
min_int=1
elts=0
size=0
#Queue wrappers
# Wrapp the queue methods to include the assertions for automated testing
def run_empty():
temp=q.empty()
if elts==0:
assert temp==True
else:
assert temp==False
return temp
def run_full():
temp=q.full()
if elts==size:
assert temp==True
else:
assert temp==False
return temp
def run_enqueue(val):
temp=q.enqueue(val)
if isinstance(val,int) and elts<size:
elts+=1
assert temp==True
else:
assert temp==False
return temp
def run_dequeue():
temp=q.dequeue()
if elts>0:
elts-=1
assert temp!=None and isinstance(temp,int)
else:
assert temp==None
return temp
# Random testing stuff
def get_int(): # Return a random valid integer
return random.randint(min_int,max_int)
def get_command(): #Return a random valid command (string)
return random.choice(["empty","full","enqueue","dequeue"])
def run_random_command(): # Execute a random command
c=get_command()
if c=="empty":
run_empty()
elif c=="full":
run_full()
elif c=="enqueue":
run_enqueue(get_int())
elif c=="dequeue":
run_dequeue()
else:
raise Exception("Error run command invalid command")
def test_this(ncommands=100): # Randomly test a queue with ncommands commands
run_empty()
testi=get_int()
run_enqueue(testi)
testi2=run_dequeue()
assert testi == testi2
for c in range(ncommands):
run_random_command()
#Test Code: Do it random tests each one with a diferent random queue
for it in range(iters):
size=get_int()
elts=0
q=Queue(size)
test_this()
If you assign to a variable within a function, Python automatically makes it local. You'll need to explicitly mark them as global within the child functions. (In Python 3, you can use nonlocal for that.)
However, I can't help thinking that you should really be using a class here.

Categories