How do I stub functions 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 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.

Related

check unreachable code in most simple way 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 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.

Is indirect recursion possible 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 1 year ago.
Improve this question
I tried searching online but did not find any answer to this particular question. In python there are no function declarations and a function can't be used until it has been defined.
Does this mean that indirect recursion is impossible in python?
And is there a way around this by using some modules?
No, it is possible
def f():
print('from f')
g()
def g():
print('from g')
f()
"a function can't be used until it has been defined" is not so straightforward. When the code runs, the name of the objects that it refers to have to exist. So, you can't do
f()
def f():...
because f() actually executes something. But definitions create a function object, without running it at the time. In the example, the function is claled at the last line of the script, and, by that time, both f, g do exist.

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})

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.

how can i use a variable in a function in a global variable? [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 have been trying to get some stats in a text based game i have been making. i tried to return the variable from the function but every time i try to put it in a global variable i get a name error. I have looked up many topics about this but what i found didn't help me much. Here is the code i made to try and fix the game.
def HEALTH():
health =['''
===============''','''
==============''','''
=============''','''
============''','''
===========''','''
==========''','''
=========''','''
========''','''
=======''','''
======''','''
=====''','''
====''','''
===''','''
==''','''
=''','''
x''']
return health
health =HEALTH(health)
print(health[0])
In your function definition HEALTH takes no arguments. Thus, the following line is bound to fail:
health =HEALTH(health)
In fact, this line looks more like you are trying to create a class named HEALTH but it's especially bound to fail because you are using the variable you are defining as an argument to the function health.
Probably what you are trying to do is accept an argument in the function definition:
def HEALTH(health_level):
health=['''...''']]
return health[health_level]
print(HEALTH(0))
We should have some better names for stuff too. Why not call your function something like the following:
def get_health(health_level):
health=['''...''']
return health[health_level]
That way you're not simply using the word "health" over and over again in possibly confusing ways.
Also, I think you've misunderstood a python coding convention. Typically ALL_CAPS names are reserved for CONSTANTS - variables you don't expect uses to change. For example you might have a starter value for health like this:
HEALTH_DEFAULT = 100
class Character(object):
def __init__(self):
self.Health = HEALTH_DEFAULT
class BuffCharacter(Character):
def __init__(self):
self.Health = HEALTH_DEFAULT * 2
in your case, it looks like you're trying to keep an index of graphic printouts of health for a range of values. You probably want more like this:
HEALTH_DISPLAY = ["=" * i for i in range (10, 0, -1)] + ["X"] # easier on the eyes!
def get_health(val):
return HEALTH_DISPLAY[val]

Categories