python AssertionError in django - python

I am reading the http://www.djangobook.com/en/2.0/chapter04.html. I'm new to python and django but have experience with php.
I've come across the following:
>>> t = Template("My name is {{ person.first_name }}.")
>>> class PersonClass3:
... def first_name(self):
... raise AssertionError, "foo"
>>> p = PersonClass3()
>>> t.render(Context({"person": p}))
this gives the following error;
Traceback (most recent call last):
...
AssertionError: foo
would someone mind explaining why this error occurs? I'm not sure I follow what the problem is. I understand lines 1,2 and 5 but not the others.
Thank you,
Bill

Your code has done exactly what the example was trying to show. You “raised” an exception which caused your program to halt execution because there was no handler to deal with it.
This guide might be a good place to start.

Related

celery+kombu not giving a useful traceback - how to expand it?

I'm working on porting some Python 2.7 code to 3.10 (I know, it's late).
The server-side code uses:
celery==5.2.3
kombu==5.2.4
...though the client side is on something much older:
celery==3.1.26.post2
kombu==3.0.37
It appears that the server-side Celery or Kombu (they both can output the relevant error message), I don't know which, is giving a very terse traceback that I'd love to expand:
body: b'\x80\x02}q\x01(U\x07expires... (64915309b)
Traceback (most recent call last):
File "/usr/local/lib/python3.10/site-packages/celery/worker/consumer/consumer.py", line 568, in on_task_received
type_ = message.headers['task'] # protocol v2
KeyError: 'task'
(I shortened the binary data a little myself on the "body" above)
My question is, how can I find out what part of my code is triggering that traceback?
Thanks!

Is there a way to change mne.io.raw first sample information?

I want to modify my raw.first_samp which is an integer that looks like it.
Input ->
file = 'yourfilename.fif'
raw = mne.io.read_raw_fif(file)
print(raw.first_samp)
Output ->
100500
I would like to put it at 0. But when I try, this is the error I get. I have tried everything but it makes me impossible to set events the right way since they are based on the first samp.
This is the error I get.
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_27068/706203670.py in <module>
----> 1 raw.first_time = 0
AttributeError: can't set attribute
Please, I would love to have any help or suggestion concerning this issue.
If anyonye encounter this problem, I am using Python 3.9 and MNE version 0.24.
I made it work by adding this setter into the first_samp property.
#property
def first_samp(self):
"""The first data sample."""
return self._first_samps[0]
#first_samp.setter
def first_samp(self, first_samp):
self._first_samps[0] = first_samp

Can python throw a "stack overflow" error?

Can python have a stack overflow error?
Recently I was just letting my mind wander when I came across the question: "can python get the stack overflow error? Does anyone have any answers?
I searched for the answer but only found java answers. I have used java but its just not my question:
What is a StackOverflowError?
https://rollbar.com/blog/how-to-fix-java-lang-stackoverflowerror-in-java/
My Reasoning
I initially thought no because python just... works most of the time (like passing an int for a string). It also doesn't have stacks (to my knowledge). But I wasn't sure. Here I am.
Sure it can
the following code will cause a seg fault:
import sys
sys.setrecursionlimit(10_000_000)
def foo():
foo()
On Mac OS, this throws:
Segmentation fault: 11
Which is caused by a stack overflow.
You can, if your recursion limit is too high:
def foo():
return foo()
>>> foo()
Result:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
.......
File "<stdin>", line 2, in foo
RuntimeError: maximum recursion depth exceeded
>>>
The default recursion limit is 10**3 (verifiable via sys.getrecursionlimit), but you can change it using sys.setrecursionlimit:
import sys
sys.setrecursionlimit(10**8)
def foo():
foo()
but doing so could be dangerous -- the standard limit is a little conservative, but Python stackframes can be quite big.
By default, Python's recursion limit is 10**3, theoretically if you were to pass this then you would be given a RecursionError.
You can even reduce the recursion limit using setrecursionlimit() to make this happen more quickly.

Searching Sonos Music Library with SoCo in Python

I have another SoCo questions and I really hope someone can get me started.
I'm really pulling my hair out here. What am I doing wrong?
>>> from soco.music_library import MusicLibrary
>>> MusicLibrary.get_music_library_information('artists', search_term='Metallica')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: get_music_library_information() missing 1 required positional argument: 'search_type'
I copied the get_music_library_information('artists', search_term='Metallica') straight out of the docs.
Thanks for having a go Bahrom. I got it to take action in the following way:
First i got the list of speakers with a
speakers=soco.discover()
and then I selected one of the speakers, calling it 'speaker'.
>>> for speaker in speakers:
... if speaker.player_name == 'Office':
... break
Then I appended the get command on to the speaker e.g.
>>> from soco.music_library import MusicLibrary
>>> speaker.get_music_library_information('genres')
and this works :)
Haven't tested this, but looking at music_library.py on github, I think you just need to instantiate MusicLibrary first:
>>> from soco.music_library import MusicLibrary
>>> MusicLibrary().get_music_library_information('artists', search_term='Metallica')

How to test python code on command line

While writing and testing a python method, I am currently using the following approach:
import foo as f
bar = f.bar()
bar.runMyMethodAndSeeIfItWorks()
If I change something in my method, and I need to retest it, I have to execute the following:
f = reload(foo)
bar = f.bar()
bar.runMyMethodAndSeeIfItWorks()
I was wondering if there is a simpler approach to this
Write a real unit test, and run it from the command line. I find this is one of the most compelling reasons for adopting unit testing: you're going to need to try out your methods as you write them anyway, you might as well do it in a form that will be runnable for evermore after that.
You must be referring to testing from a Python shell [x] where reload is used. In that case, reload is just fine - I wouldn't worry about it. You can also have:
import foomodule
And later:
reload(foomodule)
[x] Don't just use the vanilla shell (running python on the command line) - rather try something like IPython or Spyder.
You should look into Doctests. It is a dead simple way to learn testing.
Essentially, you write your tests in the interactive interpreter, then you can copy/paste them in the docstrings of your functions.
Example (from the Python documentation)
def factorial(n):
"""Return the factorial of n, an exact integer >= 0.
If the result is small enough to fit in an int, return an int.
Else return a long.
>>> [factorial(n) for n in range(6)]
[1, 1, 2, 6, 24, 120]
>>> [factorial(long(n)) for n in range(6)]
[1, 1, 2, 6, 24, 120]
>>> factorial(30)
265252859812191058636308480000000L
>>> factorial(30L)
265252859812191058636308480000000L
>>> factorial(-1)
Traceback (most recent call last):
...
ValueError: n must be >= 0
Factorials of floats are OK, but the float must be an exact integer:
>>> factorial(30.1)
Traceback (most recent call last):
...
ValueError: n must be exact integer
>>> factorial(30.0)
265252859812191058636308480000000L
It must also not be ridiculously large:
>>> factorial(1e100)
Traceback (most recent call last):
...
OverflowError: n too large
"""
<do stuff>
if __name__ == "__main__":
import doctest
doctest.testmod()
tldr;
You precede the line of code that you want to test with '>>>' and the expected result on the line below it. There is more to it than that but this should be enough to get you started.

Categories

Resources