check unreachable code in most simple way in python [closed] - python

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 12 months ago.
Improve this question
I have a python code with is detect any errors in another python code saved in txt file, i did that i can detect magic numbers and more than 3 parameters in the function, and now i have to check un reachable code, but i don't have an idea how can i do it, i want to detect if there's a code after return in the function, i did several attempts and all of them failed
This main class :
class CodeAnalyzer:
def __init__(self, file):
self.file = file
self.file_string = ""
self.errors = {}
this is a method where it's pass detects function so i can print errors :
def process_file(self):
for i, line in enumerate(self.file):
self.file_string += line
self.check_divide_by_zero(i, line)
self.check_parameters_num(i, line)
and for example this is check parameter function, i need to write similar one but to detect unreachable code :
def check_parameters_num(self, i, line):
count = line.count(",")
if(line.startswith('def') and count+1 >= 3):
self.errors.setdefault(i, []).append(('S007', ''))
Any one can help and have an idea ?

Probably you would have to use the ast module to look at the parse tree.
Look for:
Conditions for if and while statements that are always False. (or always true in case of an else) This would involve "constant propagation", that is realizing that an expression that only depends on constants is itself constant.
Code after a return, without that return being part of an if.
Code at the end of a function that is indented incorrectly an thus in the module context.
Or you could look at how mypy is doing it.

Related

Moving turtle after mouse click [duplicate]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I have this function:
def a(one, two, the_argument_function):
if one in two:
return the_argument_function
my the_argument_function looks something like this:
def b(do_this, do_that):
print "hi."
Both of the above are imported to a file "main_functions.py" for my ultimate code to look like this:
print function_from_main(package1.a, argument, package2.b(do_this, do_that)
The "if one in two" from "a"function works but "b"function still executes when being passed to "function_from_main" without waiting the check from "a" to see if it actually should execute.
What can I do?
package2.b(do_this, do_that) is a function call (a function name followed by parenthesis). Instead you should be passing only the function name package2.b the function a
You will also need to modify function a such that function be is called when the condition is satisfied
# function a definition
def a(one, two, the_argument_function, argument_dict):
if one in two:
return the_argument_function(**argument_dict)
def b(do_this, do_that):
print "hi."
# function call for a
a(one, two, b, {'do_this': some_value, 'do_that': some_other_value})

How to update a variable inside a function? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I have a question about two different ways of writing a piece of code. I want to know whether they are both okay or one is better under some conditions? Basically, is it better to give the variable we want to update to the function or not?
def f1(num):
output.append(num)
output = []
f1(2)
print(output)
and
def f1(num, output):
output.append(num)
output = []
f1(2, output)
print(output)
In the first example, your function works for only adding element to globally defined certain array. And it is not good approach, you cannot use it for another array.
Second one has generic approach which is better. But only one small correction; you have an array named output, and you pass it to your function, but you keep its name same in your function. So, for your function, there are two output one global and one local, better use different names in this case:
output = []
def f1(num, arr):
arr.append(num)
f1(2, output)
print(output)
Please see warning PyCharm shows in same naming case:
Consider avoiding to use the first example where possible: global variables can be very difficult to work with, generating problems you never find easily. Instead, use the second piece of code.
You could also write something like the following code:
output = []
def add(num, listName):
listName.append(num)
return listname
for _ in range(5):
output = add(_, output)
print(output)

How do I stub functions in python? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
It's my first few lessons in programming and i've encountered a question that i don't really understand how to proceed.
def defeat_balrog(protagonist):
def spawn_balrog():
"""Spawns and returns a stubborn balrog"""
pass
def balrog_attack(balrog, person):
"""Returns an attack move from the balrog's repertoire"""
pass
cave_balrog = spawn_balrog()
is_balrog_defeated = False
yell(protagonist, 'You cannot pass!')
while not is_balrog_defeated:
current_attack = balrog_attack(cave_balrog, protagonist)
if current_attack != None:
take_defensive_action(protagonist, current_attack)
yell(protagonist, 'YOU SHALL NOT PASS!')
take_offensive_action(protagonist, cave_balrog)
is_balrog_defeated = True
return True
def take_defensive_action(attacked_entity, attack_move):
"""
attacked_entity anticipates attack_move and defends himself.
"""
pass
#my stubs here#
defeat_balrog('gandalf')
I'm supposed to identify the remaining functions that have been wishfully used, but for which stubs have not been created, and fill in from the last line #my stubs here#. not sure how to get started or proceed on.
A stub is a function that exists but for which no meaningful business logic has been defined. For example:
def take_defensive_action(attacked_entity, attack_move):
pass
Notice the pass statement here? It means that you've defined a valid function, but it does nothing.
Pasting your code into PyCharm, I see the following functions highlighted in "yellow" (that means those function names have an Unresolved reference):
yell(protagonist, 'YOU SHALL NOT PASS!')
take_offensive_action(protagonist, cave_balrog)
Clear on the meaning of what a stub is, you should be able to define these functions accordingly as they haven't been defined yet. Here's an example for yell:
def yell(protagonist, message):
pass
I leave the second to you.

Passing strings to functions [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I know this is a stupid question but I don't know exactly how to search for it.
I want to feed a parameter into a function to conditionally run code.
In the example below, if I specify the word single in the function call, I would like it to run the line of code at the top and return the string "This". If I specify any other word, I want it to run the second line of code and return "That".
Example:
def condfunc(myvar):
if myvar == single:
something = "This"
else:
something = "That"
return something
mysomething = condfunc(single)
I keep getting:
NameError: name 'single' is not defined
I think you are trying to test which of two strings the argument myvar is? In that case, the code should look like:
def condfunc(myvar):
if myvar == "single":
something = "This"
else:
something = "That"
return something
which can be simplified to:
def condfunc(myvar):
return "This" if myvar == "single" else "That"
and you would call it, e.g.:
test = "single"
mysomething = condfunc(test)

Python: Call an object from 'n string value [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I sincerely hope this is not a duplicate, but I cannot find an answer (you'll notice that I don't even know how to ask the question!).
I have python code with one class and many def. It would take too much time to explain why I would want to do the following, but I sure would be able to:
class A:
def a(self):
some argument
def b(self):
another argument
So to call the def's, I just put:
A().a()
A().b()
What I would like to do is have a third def that looks like this:
def c(self):
process = [A().a(), A().b(), A().a(), A().a()] #This sequence is just an example - there are many more def's.
for i in process:
print 'Hello'
i
print 'Bye'
I don't know if this makes any sense? What happens currently is the process part is called and the two print lines are printed several times thereafter.
Thanks.
Might this work?
def c(self):
process = [self.a, self.b, self.a, self.a]
for i in process:
print 'Hello'
i()
print 'Bye'
In your original example, instead of storing the functions, you were calling them already when the list was built. The return values from your methods got stored in the list, so that is why they could not be called later.

Categories