I tried to simulate a diagram and it works for most of the time.
builder = DiagramBuilder()
...
diagram = builder.Build()
simulator = Simulator(diagram)
try:
simulator.Initialize()
simulator.AdvanceTo(float(1.5))
except RuntimeError:
pass
Until at some point, the drake simulation will terminate at 0.2000000s and return a TypeError.
simulator.AdvanceTo(float(1.5))
TypeError: AdvanceTo(): incompatible function arguments. The following argument types are supported:
1. (self: pydrake.systems.analysis.Simulator_[float], boundary_time: float) -> pydrake.systems.analysis.SimulatorStatus
Invoked with: <pydrake.systems.analysis.Simulator_[float] object at 0x7f59bbf169f0>, 1.5
I haven't seen this one before. I have tried many parameters but all simulations stop at 0.200000 second.
Am I missing anything, or what method should I try to debug?
*Edit
I figured out why the Simulator is unhappy with my setup. The parameter is correctly passed to Simulator but there is something wrong with one LeafSystem in my diagram.
In my diagram, there are discrete ports connected to each other. When a value is passed to a discrete LeafSystem, the system needs to call a function to update values (set_value() ) and return those values by a pointer. However, the function do need to return a status by which indicate the diagram the value update has been done. Therefore, EventStatus.Succeeded() is required to be returned if the update is successful.
Nevertheless, I have no idea why lack of status return will result into a TypeError. I'm to be honest, fairly new to drake so I might have a bad explanation. Willing to receive any professional comments.
Related
Background
I am new to python and I am writing a simple function but I am also interested in learning to do things the correct / pythonic way as I progress in my journey.
Lets consider the function below
def test_func(nested_lists,val):
return
I am expecting two arguments. One argument would be a list containing more lists. Something like this [[1,2,3,],[4,5,6,]...]. The second argument could be a value like 1.
If someone say for instance passes in a single value as the first argument and an array as the second argument. My code as it is currently returning the correct output which is 0 , However is there another way that i should be handle this?
For example should I be doing something like this
if(type(value) == list):
return 0
Or do i not need to do anything because my function is returning 0 anyway.
I know this maybe a very basic question so please forgive me but coming from a java background I am new to python so i am not sure how to handle such scenarios in python.
The other answer illustrates the proper way to check in advance for problems you can foresee. I'll provide a different approach.
The idiomatic solution in python is to "ask forgiveness, not permission". There are a lot of things that can go wrong, and where other languages might ask you to foresee all those problems and address them manually, python encourages just handling them as they happen. I would recommend doing:
def test_func(nested_lists, val):
try:
...
except TypeError:
# do whatever error-handling behavior you need to
# either throw a custom exception or return a specific value or whatever
return 0
and then designing your code in such a way that, if nested_lists and values are not compatible types, then they throw a TypeError (e.g. trying to iterate through nested_lists should fail if nested_lists is not a list. You can experiment with this behavior in a python console, but in general trying to do something to a variable that doesn't work because it's not the right type will produce a TypeError).
If your current code is working correctly, there is no pressing need to change anything. However, there are some reasons you might want to code more defensively;
If the code will seem to work correctly when you pass in bogus values, it would be better if it raised an exception instead of return a bogus value. The responsibility to call it correctly lies squarely with the caller, but enforcing it can help make sure the code is correct.
if not isinstance(nested_lists,list):
raise ValueError('Need a list, got {0!r}'.format(nested_lists))
This has the drawback that it hardcodes list as the type for the first argument; properly reusable code should work with any type, as long as it has the required methods and behaviors to remain compatible with your implementation. Perhaps instead check for a behavior:
try:
something involving nested_lists[0][0]
except (IndexError, AttributeError):
raise ValueError('Expected nested list but got {0!r}'.format(nested_lists))
(The try is not strictly necessary here; but see below.)
If you get a traceback when you call the code incorrectly, but it is opaque or misleading, it is more helpful to catch and explicitly point out the error earlier. #or example, the snippet above (without the try wrapper) would produce
Traceback (most recent call last):
module __main__ line 141
traceback.print_exc()
module <module> line 1
test_func(1,1)
module <module> line 2
AttributeError: 'int' object has no attribute '__getitem__'
which is somewhat unobvious to debug.
If the code will be used by third parties, both of the above considerations will be more important from a support point of view, too.
Notice how the code raises an exception when called incorrectly. This is generally better than silently returning some garbage value, and the caller can similarly trap the error with a try/except if this is well-defined (i.e. documented!) behavior.
Finally, since Python 3.5, you have the option to use type annotations:
def test_func(nested_lists: list, val: int) -> int:
...
As noted in the documentation, the core language does not (yet?) enforce these type checks, but they can help static code analysis tools point out possible errors.
I am interested in Python and started reading Think Python by Allen B. Downey. I am a complete beginner and do not know anyone in my circle of friends who programs so I decided I will ask my question here, however simple it may be.
I am currently in the section related to Functions and can not make sense of an example/exercise which involves concatenation:
def cat_twice(part1, part2):
cat = part1 + part2
print_twice(cat)
In the book this is described as storing a local variable in a function. In previous chapters of the same book all exercises are done in the Python Shell IDLE. As far as I understood in order to call a function after something is stored in it you do this:
cat_twice()
Yet when I do this I get:
Traceback (most recent call last):
File "<pyshell#63>", line 1, in <module>
cat_twice()
TypeError: cat_twice() missing 2 required positional arguments: 'part1' and 'part2'.
What exactly am I not getting or doing wrong? why isn't the program running?
What you are doing here is, your function is expecting two arguments, i.e., part1 and part2, compulsorily. When you are calling your function, you have to call as follows:
cat_twice(1,2) # assuming are trying to add two numbers in your function
If you are trying string concatenation, I would recommend you to look up join() function in python.
If you want to have a variadic function which can take either of part1 or part2 as an argument, or both or none of them, you can assign certain default value in method signature, for example,
def cat_twice(part1=None, part2=None)
...
...
...
if __name__ == '__main__':
cat_twice(part1=<something>)
cat_twice(part2=<somethingElse>)
cat_twice(part2=<some>, part1=<someMore>)
cat_twice(1,2) # here 1 will be passed as part1 and 2 as part2
Keep in mind that if you have assigned None as default to function parameters, the have a None check before performing addition operation or you may lead into TypeError for adding unsupported operand types.
I hope this is helpful.
Here a Simple Example, i have defined a function cat_twice which will print two values that are passed to it.
Then i passed two values by calling it like cat_twice() simple :) .
def cat_twice(part1,part2):
print(part1+part2) #this is the code in the function that will execute
cat_twice(1,2) #this is known as calling function
The "cat_twice" function contains the function "print_twice".
Be sure that python has run this function first, so that "cat_twice" can reach "print_twice" when it needs to.
It can be included at the start of the block.
Try:
def print_twice(bruce):
print(bruce)
print(bruce)
"""Defines the print_twice function"""
def cat_twice(part1,part2):
cat=part1+part2
"""the print_twice function now feeds into line 9"""
print_twice(cat)
line1='bingtiddle'
line2='tiddlebang'
cat_twice(line1,line2)
I am also alone in learning python, I did a few bootcamp course on Udemy.
Think Python is a far better book for actual learning.
This is the first advice I have felt confident enough to give, so I hope it works.
I have reached chapter 4 so far.
Good luck
I recently bumped into a "feature" of Python which I found not really well thought-out: Python raises TypeError if a function is called with the wrong number of arguments. I would like to understand what is the reason behind this choice.
Further details:
I find myself setting-up a callback system and, among other things, I check if a (user-defined) callback can accept or not an argument. I have to check this up-front when I am given the callback, because if I simply do something like:
try:
call_the_callback(one_argument)
except TypeError:
call_the_callback()
except Exception:
do_something_else()
I find myself in the uncomfortable situation of catching also a TypeError thrown by the inside-workings of the callback (maybe it expected a string instead of an integer, or something), which I definitely need to discriminate.
In the end, I bypassed this with a check as follows (I guess this is only for Python 3):
callsign = signature(action)
nargs = len(callsign.parameters)
and then using the appropriate call. However, apart from this specific problem, I simply cannot understand why putting under the same umbrella a call with the wrong number of arguments and, say, 1 / "three".
NOTE: I understand why an error is raised for a call with the wrong number of arguments, I definitely want that! My problem is with understanding why a TypeError is raised and not something more specific. I want to have a deeper understanding of this to better design strategies to tackle this kind of situation.
References:
Too generic, only saying that a call with the wrong number of arguments is "some kind of TypeError": Why TypeError when too many / too few args in Python function call
Discusses the issue but does not answer the question: https://bytes.com/topic/python/answers/45841-incorrect-number-arguments
I think almost all programming languages have mandatory parameters for a function and if those parameters are not received an exception is raised. This is good for enforcing a proper usage for that function. If function parameters are not mandatory you need more handling logic inside the function in order to cover all cases.
But you can use optional parameters or generic parameters along with or without mandatory params.
For example bellow is a function which allow you to have any number of parameters (simple or keyword parameters) and no param is mandatory:
def f1(*args, **kwargs):
print args
print kwargs
f1(1,'param', a=4)
For more details see:
generic function in python - calling a method with unknown number of arguments
I'm learning python from a textbook. This code is for the game Tic-Tac-Toe.
The full source code for the problem:
http://pastebin.com/Tf4KQpnk
The following function confuses me:
def human_move(board, human):
""" Get human move."""
legal = legal_moves(board)
move = None
while move not in legal:
move = ask_number("Where will you move? (0 - 8): ", 0, NUM_SQUARES)
if move not in legal: print "\nThat square is already taken. Choose another.\n"
print "Fine..."
return move
I do not know why the function receives 'human' parameter. It appears to do nothing with it.
def human_move(board, human):
How would I know to send 'human' to this function if I were to write this game from scratch? Because I can't see why it is sent to this function if it isn't used or returned.
The answer: it depends. In your example it seems useless to me, but I haven't checked it in depth.
If you create a function to be used only from your code, it is in fact useless.
def calculate_money(bank_name, my_dog_name):
return Bank(bank_name).money
money = calculate_money('Deutsche bank', 'Ralph')
But if you are working with some kind of API/Contract, the callbacks you specify might accept arguments that are not needed for a certain implementation, but for some others, are necessary.
For instance, imagine that the following function is used in some kind of framework, and you want the framework to show a pop up when the operation is finished. It could look something like this:
def my_cool_callback(names, accounts, context):
# do something blablab
context.show_message('operation finished')
But what if you don't really need the context object in your callback? you have to speficy it anyway for the signature to match... You can't call it pointless because that parameter is used sometimes.
EDIT
Another situation in which it could be useful, would be to loop through a list of functions that have almost the same signature. In that case could be ok also to have extra arguments as "garbage placeholders". Let's say all your functions need 3 arguments in general, but one needs only 2.
Consider
try:
f(*args, **kwargs)
except TypeError:
print "doh!"
The reason for TypeError in this case could a problem in function arguments, e.g. f() got an unexpected keyword argument 'b'. However, TypeError could also be raised due to a problem within the function body itself, e.g. list indices must be integers, not str.
I wonder if there is a solid way in Python 2 in order to distinguish both cases (problem with arguments, problem in body). Maybe some decorator-based approach?
Reasoning: I am implementing just another kind of job system. A job basically is a function. The arguments to this function could be derived from user input and go through a JSON serialization/deserialization process. I want the system to provide as exact error messages as possible to the user of the system. Hence, I would like the entity that controls job execution to be able to distinguish both sources of TypeError. Furthermore, I think this a very interesting problem itself.
I realize that https://stackoverflow.com/questions/12712475/how-to-check-if-a-typeerror-raised-from-mismatched-function-arguments basically is a duplicate of this question. However, the comment discussion there just stopped without any answers. I hope in this case it is okay to open my own question and reformulate the issue.
So I wouldn't do it the way since the internal error that you want to propagate up is a coding error, not an actual exception that needs to be caught.
That being said. I would introspect the error being thrown and and silence one and propagate the other.
I'm pretty sure you can solve this problem the following way:
Step 1. Create a custom exception (e.g. AwfulTypeError) for the in-body TypeError by subclassing Exception:
class AwfulTypeError(Exception):
pass # Or do something if necessary
Step 2. Wrap your whole function body in a try block and except TypeError for that block:
def my_function(a, b, c):
try:
# Some operations you need to do
return (a + b) * c
except TypeError as e:
# We're doing stuff here in the next step
Step 3. On catching the original TypeError exception, re-raise it as an AwfulTypeError exception that you have specified before:
except TypeError as e:
raise AwfulTypeError(e)
Now you are able to distinguish the argument TypeError, which remains a TypeError, from the in-body TypeError, which is now of type AwfulTypeError.
P.S. I am more used to Python 3, so if I've messed something up with the Python 2 syntax, feel free to notify me.