I use Google Style Python Docstrings like in this Example for my Django's project.
When i create a class and using an attributes notation in docstring, Pycharm always say - "Unresolved reference".
class Post(models.Model):
"""
Class for posts.
Attributes:
title(str): Post title.
"""
title = models.CharField(max_length=120)
I understand that PyCharm doesn't see self for title and def __init__() function and write this error, but in Django I've never seen using def __init__() for classes inherited from models.
What should I do? Is this my error or does PyCharm not see context in this case? Should I use def __init__() or something else or write docsting in another way?
PyCharm does not appear to have support for this currently. The active issue for this in JetBrains issue tracker is https://youtrack.jetbrains.com/issue/PY-16760, please consider upvoting it to get it fixed. The only workaround if you want to avoid seeing these "Unresolved reference" errors in your docstrings is to disable the inspection in Preferences > Editor > Inspections > Unresolved references.
Another option that I have tried in the past is removing the "Attributes:" header and writing my attribute documentation on the same indentation level as the rest of the docstring. This no longer gives you a warning, but you are no longer conforming 100% to the Google Docstring Style Guide.
I solved this issue by adding a '# noqa' after the 'Attributes:', because i did not want to disable the unresolved reference warning.
So this would be the final docstring:
"""
Class for posts.
Attributes: # noqa
title(str): Post title.
"""
The following works for me: In your docstrings, writing Attribute: instead of Attributes: makes the error disappear. That allows you to keep the indentation level
Related
looking at this example
#dataclass
class Something:
val1: int = 1
val2: int
VSCode with Pylance shows the error "Attributes without a default cannot follow attributes with one" in the editor. This is all good.
I have my own decorator that should enforce different constraints.
#model
class Something:
key1: Key[int]
# this violates a custom constraint on having exactly one attribute of type `Key`
key2: Key[int]
I have implemented model such that it throws an exception since there are two keys. This works too.
Now, the problem is, that the user doesn't see this error in the editor. Instead, the testing widget with pytest encounters discovery errors and the user needs to check the Python Output console to see what is going on.
How can I make violations to my custom constraints visible in the editor?
Apologies if this is a silly question, I am pretty new to python and django.
I am following along with a django tutorial, and we are creating a fake movie site that lists movies by genre, title, etc.
I am currently trying to override the __str__ function in the models.py file, so rather than displaying Genre (1), it displays the actual genre (ex. "Action").
Here's how my models.py looks currently:
from tkinter import CASCADE
from django.db import models
from django.utils import timezone
# Create your models here.
class Genre(models.Model):
name = models.CharField(max_length=255)
def __str__ (self):
return self.name
class Movie(models.Model):
title = models.CharField(max_length=255)
release_year = models.IntegerField()
number_in_stock = models.IntegerField()
daily_rate = models.FloatField()
genre = models.ForeignKey(Genre, on_delete=models.CASCADE)
date_created = models.DateTimeField(default=timezone.now)
However, vscode is underlining the
def __str__ (self):
When I hover over it, it tells me:
str does not return str pylint(E0307: invalid -str- returned
I tried looking at other solutions, but I could not find one that seemed to match my scenario, so I do apologize if this has been solved elsewhere, and I am too incompetent to understand the problem.
Thanks for your patience!
This question has a couple of good illustrations of why it's important to understand your code before you rely too heavily on IDEs and tools like pylint. I've two suggestions:
The pylint error is just a warning to indicate that your code might have a problem - it is not an absolute fact. The E0307 error says:
Used when a __str__ method returns something which is not a string.
It would be more accurate if it had said "when the pylint checker cannot be sure that you're returning a string". In this case, it's because it doesn't recognise that a Django CharField will in fact return a valid string instance. Your existing __str__ method would work perfectly fine if you ran the code - regardless of what pylint thinks.
You can work around this by forcing the return value to look like a string, e.g., with:
return str(self.name)
or
return f"{self.name}"
But it would be equally valid to disable the check for this line in pylint, with the understanding of why it reported the error. Just applying a fix found on Stack Overflow without understanding the issue is going to make it hard to debug your code in future.
There is a second, completely unrelated issue in your code which will cause you problems later, and that is this line:
from tkinter import CASCADE
I am pretty confident that this has been inserted by your IDE, without your explicitly adding it, because you tried to use CASCADE in your ForeignKey. This is the IDE trying to be helpful - unfortunately it has imported something completely useless, that can cause you problems when you try to deploy your code.
Both of these highlight an important principle: don't rely on IDEs or linters. They are not a substitute for understanding your own code.
Given a simple one to many relationship where one page can be linked to multiple errors:
class Page(Base):
...
errors = relationship('Error', back_populates='page')
class Error(Base):
...
page = relationship('Page', back_populates='errors')
I add error objects to a page object simple by
page.errors.append(error)
This works. However PyCharm warns about Error would have no reference "append".
My Question: Is this just PyCharm not understanding that Page.errors is of type list(?) and not Error or is is there something I should do better?
If someone stumbles upon the same problem: I did not notify any problems yet and so I guess it is simply pycharm not recognising the type correctly. You can simple help it by using type hints:
class Page(Base):
...
errors: list = relationship('Error', back_populates='page')
I am using PyDev to navigate the code of a relatively large Python projects. I want to view the hierarchy graph of the classes. I hit f4 to open the Hierarchy View.
But the view is completely empty, and there is nothing in it. I don't know why.
I just tested it here and it worked for me... To give an example:
Say you have:
class ClassA(object):
pass
class ClassB(ClassA):
pass
Now, with the cursor over 'ClassB' press 'F4': the hierarchy should be showing properly.
If it doesn't work for you, the first thing to check is if your code is under a 'source folder' in PyDev (i.e.: in the PYTHONPATH): See: http://www.pydev.org/manual_101_project_conf2.html for details.
Not sure if I was having the same problem as you... but I was able to get the hierarchy view to populate for some class objects, but only partial population for other class objects. Here's an example of one that wasn't working:
(notice the 'Parents' collection is blank despite being expanded)
Turns out the ones that were NOT working were due to me renaming some inherited class imported from some other module:
from module1 import ClassA as Class1
class ClassB(Class1):
pass
Understandably, this was confusing pydev. Sticking with the original names resolved the issue.
(sorry the images don't line up with the snippet.. but hopefully this helps someone)
I wonder if someone can help me. I'm explore deform and colander in a new project and was following the documentation about subclassing SchemaNode. However, whilst the documentation states that
subclass can define the following methods and attributes: preparer,
validator, default, missing, name, title, description, widget, and
after_bind.
when I define title, it doesn't seem to come through. Here is some example code that I'm using:
class LocationSchemaNode(colander.SchemaNode):
schema_type = colander.Int
title = 'Location'
missing = None
validator = colander.Range(
min=1,
min_err='Please select a valid location'
)
class PersonSchema(colander.Schema):
location_id = LocationSchemaNode()
However, when the form is rendered the label for the field is "Location Id" not "Location" as per the title defined in SchemaNode. If instead I write:
class PersonSchema(colander.Schema):
location_id = LocationSchemaNode(title="Location")
Then all appears as I want, but the documentation seems to state I don't need to do this, and if I do it kind of defeats the point of pre-defining a SchemaNode if I have to keep defining fields.
Am I missing something, or is deform doing something that it shouldn't be (I doubt that is going to be the case). Any help is much appreciated.
Keith
This appears to be a bug that was fixed: https://github.com/Pylons/colander/pull/183
Also, the patch seems to be in the latest available release of colander so an update to the latest version should fix this issue.
Correction:
The example given in that PR exactly matches this question, but the fix given didn't actually fix that exact issue! So, I filed another PR to fix that issue and used the example given in #183 as the test. You can manually patch your own copy if you can't wait for the fix to be introduced into the repo or the next release.