Converting a variable into a string creates EOF error - python

def evaluate(x):
number = str(eval(entry_drones.get()))
if x == drones :
create_drone(number)
entry_drones = Entry(frame, text = "1")
entry_drones.bind("<Return>", evaluate(drones))
I have a program that creates an error along the lines of:
number = str(eval(entry_drones.get()))
File "<string>", line 0
^
SyntaxError: unexpected EOF while parsing
I tried searching for the answer online, but they say I'm either missing a parenthesis (I've been unable to spot where it is needed) or I'm using input instead of raw_input (Neither appear to be the cause of this error, at least to my knowledge)
I posted just the code that I think is relevant to the issue, but I can provide more if needed. Take note, I have math and Tkinter imported, as well as other things.
I used eval because it is the only way I know (out of limited experience) to take the input from my Entry widget and simplify it before I run it through another function.
As for drones, it lets my evaluate function know which function to pass number to. I snipped out all of the other options because it is repetitive and it all leads to this function. entry_drones can have basic expressions put into it such as 10 * 10 or something. In my code I set k = 1000 and so forth, allowing me to use letters to abbreviate.
The entry_drones.get() should (if I'm not mistaken) grab whatever is typed into the Entry widget whenever the Enter key is pressed.

The eval function interprets the string you pass to it as Python code. You'll get a SyntaxError if anything is typed in your text entry box that isn't a valid Python expression (such as an empty string, for instance). You might get other exceptions too, if you type something that could be valid, but has other problems (for instance, calling eval on a random string that could be a variable name will probably raise a NameError since there is no such variable).
If that's the only problem, you probably just want to catch exceptions from the eval call and either ignore them or give an appropriate error message in your program.
Be aware too that calling eval on user input can be really dangerous. If a user types in something like __import__("os").system("rm -Rf /") your program might quietly delete the entire contents of your hard drive (don't try this!). This is obviously a much bigger deal if your program is running with more permissions on your system than the user would have by themselves (probably not likely for a GUI app, but very common for a web app), but even if you're only capable of doing things that the user could do anyway from a command prompt, it's a bad idea to use eval on untrusted input.
Unfortunately there isn't really a trivial way to do what I think you want (simplifying mathematical expressions, possibly including calls to functions like math.sqrt) without a bunch of work. One option would be to pass the string to ast.parse to get an abstract syntax tree, and then walk the tree to make sure it only does stuff you want to allow (such as using mathematical operators, and calling specific whitelisted functions (e.g. the ones in the math module). You can then pass the validated AST to compile and then eval it with confidence that it won't do anything bad.

eval() is very dangerous as #Blckknght explained well.
On a side note, Just to point out the actual root cause of the issue , it should be because of the line -
entry_drones.bind("<Return>", evaluate(drones))
This would run the function evalute() when this line is executed, and that is most probably before the app has even completely started, so the entry entry_drones is empty causing the issue. Then if it were to run successfully, it would pass the returned value to the bind method, in this case, None would be returned.
I believe if you want to send a parameter to your evaluate() function, then you should first make it accept more than one paraemter, since bind itself sends it event parameter. Example -
def evaluate(event, x):
...
Then use lambda expression with default value to pass the drones into x. Example -
entry_drones.bind("<Return>", lambda event, x=drones: evaluate(event, x))

Related

Using exec() to get class instances

I have a class and I need to use string input to create it and I've heard about exec(), so I tried using that and I put the string in properly yet it gives me errors, this is the exec line:
exec(" ".join(args[2:])).toString()
The first 2 parts of the list are not relevant. I debugged this string just to see it is correct and even tried to hardcode it and it worked, but it didn't when I used exec.
What is wrong with this and how can I make this right?
Appreciating all the comment :)
Edit:
The error I get is AttributeError saying it is a NoneType, although if I just hardcode it it works perfectly fine.
Solution 1: instead of passing a Python expression, either use argparse's subcommands or define your own easily-parsable mini-language. You can store relevant classes and functions in a dict to get them from strings (better than relying on globals as it lets you whitelist only what you want to expose)
Solution 2: use the full power of the ast module to parse the Python expression into an ast then write your own visitors to safely evaluate the ast.
Solution 3: keep on using exec or eval and wait until some script kiddie erases your full hard-drive or worse.

When to type-check a function's arguments?

I'm asking about situations where if a wrong type of argument is passed to the function, it could:
Blow up the whole thing.
Return unexpected results
Return nothing
For instance, the function below expects the argument name to be a string. It would throw an exception for all other types that doesn't have a startswith method.
def fruits(name):
if name.startswith('O'):
print('Is it Orange?')
There are other cases where a function could halt or cause damage to the system if execution proceeds without type-checking. Whenever there are a lot of functions or functions with a lot of arguments, type checking is tedious and makes the code unreadable. So, is there a standard for doing this? As to 'how to type check' - there are plenty of examples here on stackexchange, but I couldn't find any about where it would be appropriate to do so.
Another example would be:
def fruits(names):
with open('important_file.txt', 'r+') as fil:
for name in names:
if name in fil:
# Edit the file
Here if the name is a string each character in it will influence the editing of the file. If it is any other iterable, each element provided by it would influence the editing. Both of these could produce different results.
So, when should we type-check an argument and should we not?
The answer off the top of my head would be: it depends where the input comes from.
If the functions are class methods that get invokes internally or things like that, you can assume the inputs are valid, because you wrote it!
For example
def add(x,y):
return x + y
def multiply(a,b):
product = 0
for i in range(a):
product = add(product, b)
return product
In my add function, I could check that there is a + operator for the parameters x and y. But since I wrote the multiply function, and that is the only function that uses add, it is safe to assume the inputs will be int because that's how I wrote it. Now that argument stands on shaky ground for large code bases where you (hopefully) have shared code, so you can't be sure people don't misuse your functions. But that's why you comment them well to describe the correct use of said function.
If it has to read from a file, get user input, etc, then you may want to do some validation first.
I almost never do type checking in Python. In accordance with Pythonic philosophy I assume that me and other programmers are adult people capable of reading the code (or at least the documentation) and using it properly. I assume that we test our code before we let it destroy something important. After all in most cases if you do something wrong, you'll just see an error and Python's error messages are quite informative most of the time.
The only occasion when I sometimes check types is when I want my function to behave differently depending on the argument's type. But although I sometimes feel compelled to do this, I don't consider it a good practice.
Most often it happens when my function iterates over a list of strings and I fear (or want) I could get a single string passed into it by accident - this won't throw an error at once because unfortunately string is an iterable too.

How to SkippCall while Hooking in Deviare?

Does anyone how to SkipCall() in Deviare (Python)?
They say something like:
HRESULT SkipCall ()
Skip calling the original function.
When I try to do this, it doesn't work. It goes in a loop at the same call. I guess that I should also do some stuff on registers (like to restore EBP). But the thing is that NktCallInfo.Register set doesn't work in Python. I try something like:
NktHookCallInfo.Register(ESP, EBP)
But it doesn't work. Help please ?
I recently see this question. Expect not to be late. (I'm a Deviare developer)
When you call SkipCall, you must setup a return value and, optionally the Win32 lasterror using the provided 'INktHookCallInfo' methods. If the function being hooked is in the database, it will remove the parameters from stack depending on the calling convention.
If you are hooking an arbitrary address without assigning a function, you must do the unwind manually by setting the ESP/RSP registers as appropiate.

Docstrings - one line vs multiple line

I'm adding some (epydoc) documentation to a package I've written, and I'm coming across a lot of instances where I'm repeating myself a multitude of times.
def script_running(self, script):
"""Return if script is running
#param script: Script to check whether running
#return: B{True} if script is running, B{False} otherwise
#rtype: C{bool}
"""
PEP257 says that:
One-liners are for really obvious cases.
and also
The docstring for a function or method should summarize its behavior and document its arguments, return value(s), side effects, exceptions raised, and restrictions on when it can be called (all if applicable).
Is there a general guideline or standard practice for when to draw the line between a one-liner (description) and full param/return fields?
Or when generating documentation should I include every applicable field for each function, regardless of how repetitive it seems?
Bonus question: Syntactically, what's the best way to describe the script param?
The general guideline you are looking for is right in PEP257 in what you quoted, maybe you just need to see it in action.
Your function is a good candidate for a one-line docstring ("really obvious cases"):
def script_running(self, script):
"""Check if the script is running."""
Usually if you say that a function is checking something it means that it's going to return True or False, but if you like you could be more specific:
def script_running(self, script):
"""Return True if the script is running, False otherwise."""
Once again all in one line.
I would probably also change the name of your function, because there's no need to emphasize on what the function works in its name (a script). A function name should be something sweet, short and meaningful about what the function does. Probably I'd go with:
def check_running(self, script):
"""Return True if the script is running, False otherwise."""
Sometimes the function-name-imagination is tired by all the coding, but you should try anyway to do your best.
For a multiline example, let me borrow a docstring from the google guidelines:
def fetch_bigtable_rows(big_table, keys, other_silly_variable=None):
"""Fetches rows from a Bigtable.
Retrieves rows pertaining to the given keys from the Table instance
represented by big_table. Silly things may happen if
other_silly_variable is not None.
Args:
big_table: An open Bigtable Table instance.
keys: A sequence of strings representing the key of each table row
to fetch.
other_silly_variable: Another optional variable, that has a much
longer name than the other args, and which does nothing.
Returns:
A dict mapping keys to the corresponding table row data
fetched. Each row is represented as a tuple of strings. For
example:
{'Serak': ('Rigel VII', 'Preparer'),
'Zim': ('Irk', 'Invader'),
'Lrrr': ('Omicron Persei 8', 'Emperor')}
If a key from the keys argument is missing from the dictionary,
then that row was not found in the table.
Raises:
IOError: An error occurred accessing the bigtable.Table object.
"""
This could be one way to "summarize its behavior and document its arguments, return value(s), side effects, exceptions raised, and restrictions on when it can be called (all if applicable)".
You might also be interested to look at this example of pypi project that it's meant to be documented with Sphinx.
My 2 cents: Guidelines are meant to give you an idea about what you should and shouldn't do, but they are not strict rules that you have to blindly follow. So at the end choose what you feel to be better.
I would like to clear something that is been said in another answer about hitting the Maximum Line Length with a docstring.
PEP8 tells you to "Limit all lines to a maximum of 79 characters" even though at the end everyone does 80.
This are 80 characters:
--------------------------------------------------------------------------------
And this may be an edge case where a little long one sentence is all you really need:
def my_long_doc_function(arg1, arg2):
"""This docstring is long, it's a little looonger than the 80 characters
limit.
"""
Is like a one-line docstring, meaning that is for really obvious cases, but on your editor (with the 80 character limit) is on multiple lines.
I think there is likely always some degree of repetition involved when adding extended syntax for docstrings, i.e. epydoc/sphinx markup.
I would also say this matter is subjective rahter than objective. Explicit is better than implicit, and would seem to follow the Zen of Python more.

Hot swapping python code (duck type functions?)

I've been thinking about this far too long and haven't gotten any idea, maybe some of you can help.
I have a folder of python scripts, all of which have the same surrounding body (literally, I generated it from a shell script), but have one chunk that's different than all of them. In other words:
Top piece of code (always the same)
Middle piece of code (changes from file to file)
Bottom piece of code (always the same)
And I realized today that this is a bad idea, for example, if I want to change something from the top or bottom sections, I need to write a shell script to do it. (Not that that's hard, it just seems like it's very bad code wise).
So what I want to do, is have one outer python script that is like this:
Top piece of code
Dynamic function that calls the middle piece of code (based on a parameter)
Bottom piece of code
And then every other python file in the folder can simply be the middle piece of code. However, normal module wouldn't work here (unless I'm mistaken), because I would get the code I need to execute from the arguement, which would be a string, and thus I wouldn't know which function to run until runtime.
So I thought up two more solutions:
I could write up a bunch of if statements, one to run each script based on a certain parameter. I rejected this, as it's even worse than the previous design.
I could use:
os.command(sys.argv[0] scriptName.py)
which would run the script, but calling python to call python doesn't seem very elegant to me.
So does anyone have any other ideas? Thank you.
If you know the name of the function as a string and the name of module as a string, then you can do
mod = __import__(module_name)
fn = getattr(mod, fn_name)
fn()
Another possible solution is to have each of your repetitive files import the functionality from the main file
from topAndBottom import top, bottom
top()
# do middle stuff
bottom()
In addition to the several answers already posted, consider the Template Method design pattern: make an abstract class such as
class Base(object):
def top(self): ...
def bottom(self): ...
def middle(self): raise NotImplementedError
def doit(self):
self.top()
self.middle()
self.bottom()
Every pluggable module then makes a class which inherits from this Base and must override middle with the relevant code.
Perhaps not warranted for this simple case (you do still have to import the right module in order to instantiate its class and call doit on it), but still worth keeping in mind (together with its many Pythonic variations, which I have amply explained in many tech talks now available on youtube) for cases where the number or complexity of "pluggable pieces" keeps growing -- Template Method (despite its horrid name;-) is a solid, well-proven and highly scalable pattern [[sometimes a tad too rigid, but that's exactly what I address in those many tech talks -- and that problem doesn't apply to this specific use case]].
However, normal module wouldn't work here (unless I'm mistaken), because I would get the code I need to execute from the arguement, which would be a string, and thus I wouldn't know which function to run until runtime.
It will work just fine - use __import__ builtin or, if you have very complex layout, imp module to import your script. And then you can get the function by module.__dict__[funcname] for example.
Importing a module (as explained in other answers) is definitely the cleaner way to do this, but if for some reason that doesn't work, as long as you're not doing anything too weird you can use exec. It basically runs the content of another file as if it were included in the current file at the point where exec is called. It's the closest thing Python has to a source statement of the kind included in many shells. As a bare minimum, something like this should work:
exec(open(filename).read(None))
How about this?
function do_thing_one():
pass
function do_thing_two():
pass
dispatch = { "one" : do_thing_one,
"two" : do_thing_two,
}
# do something to get your string from the command line (optparse, argv, whatever)
# and put it in variable "mystring"
# do top thing
f = dispatch[mystring]
f()
# do bottom thing

Categories

Resources