I wanted to take a look at python/pygame today, and downloaded pydev as my IDE.
Pretty satisfied overall, but it seems to be missing autocompletion for the pygame classes.
On the "screen" variable it only lists all the "x" functions, which I guess are the default class object functions.
The pydev folder is added to the PYTHONPATH.
import os, sys
import pygame
from pygame.locals import *
class Main:
background_colour = (255,0,255)
def __init__(self):
pygame.init();
self.screen = pygame.display.set_mode((500, 500));
self.screen.fill(self.background_colour);
pygame.display.flip();
running = True
while running:
self.update();
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
def update(self):
pass
if __name__ == '__main__':
Main()
The code works flawlessy, but ecspecially for a pygame/python noob like myself it is unbearable without any code completion.
The problem is that pydev does not know which type self.screen is of.
One workaround is using a local variable and assert isinstance(...) to help pydev.
Related
Currently I use the following setup to import pytest fixtures from a file called fixtures.py and run tests with them:
from django.contrib.auth.models import User, Group
from django.core import mail
from main.tests.fixtures import user_a, group_dropoff_for_qc
def test_should_check_password(db, user_a: User) -> None:
user_a.set_password("secret")
assert user_a.check_password("secret") is True
# more tests here
As I write more tests and use more fixtures, that import list from main.tests.fixtures grows really long. Is there some built-in pytest way around this? This seems like such a common operation that there should be a more streamlined approach.
Found the answer on my own, so here is the solution in case this helps anyone else.
Solution source: https://www.tutorialspoint.com/pytest/pytest_conftest_py.htm
If you rename an exterior file that contains fixtures to conftest.py, you can reference the fixtures in that file without needing to explicitly import them. So in my case above, I just had to rename my fixtures.py to conftest.py, which allowed me to run the tests as expected, without the import statement:
from django.contrib.auth.models import User, Group
from django.core import mail
def test_should_check_password(db, user_a: User) -> None:
user_a.set_password("secret")
assert user_a.check_password("secret") is True
# more code here
What is the benefit of importing from __future__ import annotations? When I understand it right I should stop unnecessary typing import in runtime.
In my example HelloWorld is only needed for typing. But with this code the output always is:
Should this happen?
x = World!
When I remove from hello import HelloWorld the typing help in PyCharm does not longer work (I can understand this, because it does not understand where HelloWorld is from).
from __future__ import annotations
from hello import HelloWorld
if __name__ == '__main__':
def hello(x: str, hello: HelloWorld = None):
if hello is not None:
print('hello.data_01 =', hello.data_01)
print('x =', x)
hello('World!')
hello.py
from dataclasses import dataclass
#dataclass
class HelloWorld:
data_01: str
data_02: str
print("Should this happen?")
So my question is if I still need to do from hello import HelloWorld what benefits do I get from from __future__ import annotations?
The from __future__ import annotations import has one core advantage: it makes using forward references cleaner.
For example, consider this (currently broken) program.
# Error! MyClass has not been defined yet in the global scope
def foo(x: MyClass) -> None:
pass
class MyClass:
# Error! MyClass is not defined yet, in the class scope
def return_copy(self) -> MyClass:
pass
This program will actually crash when you try running it at runtime: you've tried using 'MyClass' before it's actually ever defined. In order to fix this before, you had to either use the type-comment syntax or wrap each 'MyClass' in a string to create a forward reference:
def foo(x: "MyClass") -> None:
pass
class MyClass:
def return_copy(self) -> "MyClass":
pass
Although this works, it feels very janky. Types should be types: we shouldn't need to have to manually convert certain types into strings just to make types play nicely with the Python runtime.
We can fix this by including the from __future__ import annotations import: that line automatically makes all types a string at runtime. This lets us write code that looks like the first example without it crashing: since each type hint is actually a string at runtime, we're no longer referencing something that doesn't exist yet.
And typecheckers like mypy or Pycharm won't care: to them, the type looks the same no matter how Python itself chooses to represent it.
One thing to note is that this import does not, by itself, let us avoid importing things. It simply makes it cleaner when doing so.
For example, consider the following:
from expensive_to_import_module import MyType
def blah(x: MyType) -> None: ...
If expensive_to_import_module does a lot of startup logic, that might mean it takes a non-negligible amount of time to import MyType. This won't really make a difference once the program is actually running, but it does make the time-to-start slower. This can feel particularly bad if you're trying to write short-lived command-line style programs: the act of adding type hints can sometimes make your program feel more sluggish when starting up.
We could fix this by making MyType a string while hiding the import behind an if TYPE_CHECKING guard, like so:
from typing import TYPE_CHECKING
# TYPE_CHECKING is False at runtime, but treated as True by type checkers.
# So the Python interpreters won't do the expensive import, but the type checker
# will still understand where MyType came from!
if TYPE_CHECKING:
from expensive_to_import_module import MyType
# This is a string reference, so we don't attempt to actually use MyType
# at runtime.
def blah(x: "MyType") -> None: ...
This works, but again looks clunky. Why should we need to add quotes around the last type? The annotations future import makes the syntax for doing this a little smoother:
from __future__ import annotations
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from expensive_to_import_module import MyType
# Hooray, no more quotes!
def blah(x: MyType) -> None: ...
Depending on your point-of-view, this may not seem like a huge win. But it does help make using type hints much more ergonomic, makes them feel more "integrated" into Python, and (once these become enabled by default) removes a common stumbling block newcomers to PEP 484 tend to trip over.
New to Intellij IDEA/Scala so I'm wondering is there shortcut to auto import Scala packages.
Example:
package test
object TestClass extends App{
var i = pow(22,22)
println("Hello World" + i );
}
It wont compile until import statment is added
import scala.math._
Coming from Eclipse/Java I expected CRTL + Shift O (or auto import) would offered me math package, must I type import myself ?
Sometimes yes, sometimes no. It depends on what you're searching for.
If you write math IntelliJ doesn't know what that is. If you write Math., that's already in scope and it will offer a menu of methods on the Math object.
If you write Date, alt-enter should bring up a menu of import options. Choose one and the import statement will be inserted into your code.
No, not necessarily.
In your settings in IntelliJ you can set up auto import by following these instructions. Alternatively, when you try and use a package that you do not have imported, it will tell you that it does not recognize what you are doing and show a red error. You can then autofill from the error (typically hit alt+enter) and it should solve the issue.
I have a multi-project Scala workspace in eclipse. I think I'm getting hosed by my lack of understanding of the way Scala imports packages, but after spending more time than I care to admit looking for a solution, I can't figure this one out. I have recreated the problem in a simple 2 project setup.
Project 1: com.foo.mathematics contains a simple Vector class
Contains one file:
package com.foo.mathematics
class Vector2D(x : Double, y : Double) {
def length = math.sqrt(x*x + y*y)
}
Project 2: com.foo.analysis
package com.foo.analysis
import com.foo.mathematics.Vector2D
class Frame(xAxis : Vector2D, yAxis : Vector2D) {
}
Eclipse shows an error in the import line, The error message that I get is: Object mathematics is not a member of the package com.foo.
In the outline view, my import statement says this:
com.foo.analysis.<error: <none>>.Vector2D
I have tried changing the import to:
import mathematics.Vector2D
import _root_.com.foo.mathematics.Vector2D
neither one works...
What am I missing?
Both import com.foo.mathmatics.Vector2D and import _root_.com.foo.mathmatics.Vector2D should be fine. Most likely you either haven't added the first project to the build path of the second (see Build Path > Configure Build Path in the context menu), or need to clean the second project (Project > Build Clean) after making changes in the first project.
(Also, mathmatics looks like a typo for mathematics, so double check that you really have the same name in both places.)
Relative package imports don't come into it, they just mean you could write it this way:
package com.foo
package analysis
import mathmatics.Vector2D
class Frame(xAxis : Vector2D, yAxis : Vector2D) {
}
here is my test case , while i right click the file eclipse doest not show any run as junit test option. I try to manual create run configuration but does not take any sense.
scala version:2.8.1 scalatest:1.3 eclipse:3.6.2
package org.jilen.cache.segment
import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner
import org.scalatest.FlatSpec
import org.scalatest.matchers.ShouldMatchers
#RunWith(classOf[JUnitRunner])
class RandomSegmentSpec extends FlatSpec with ShouldMatchers {
val option = SegmentOptions()
"A Simple Segment" should "contains (douglas,lea) after put into" in {
val segment = RandomSegment.newSegment(option)
segment.put("douglas", "lea")
segment("douglas") should be("lea")
}
it should "return null after (douglas,lea) is remove" in {
val segment = RandomSegment.newSegment(option)
segment.put("douglas", "lea")
segment -= ("douglas")
segment("douglas") should equal(null)
}
it should "contains nothing after clear" in {
val segment = RandomSegment.newSegment(option)
segment.put("jilen", "zhang")
segment.put(10, "ten")
segment += ("douglas" -> "lea")
segment += ("20" -> 20)
segment.clear()
segment.isEmpty should be(true)
}
}
I've encountered this seemingly randomly, and I think I've finally figured out why.
Unfortunately the plugin doesn't yet change package declarations when you move files, nor the class names when you rename files. (Given you can put multiple classes in one file, the latter will likely never be done.) If you are used to the renamings being done automagically in Eclipse, like I am, you're bound to get caught on this.
So... check carefully the following:
the package declaration in your Scala file matches the Eclipse package name
the name of the test class in the Scala file matches the name of the Scala file
I just ran into this, fixed both, and now my test runs!
This is a known problem with the Eclipse IDE for Scala. I'm currently working on the plugin for this. Watch this space.
I found Scalatest to be very bad at integrating with Eclipse (running the tests from eclipse showed that it ran them - but they would not pass or fail, but simply show up as passive blank boxes).
For some reason I could NOT get it to work after 3 hours of trying things!
Finally I tried specs2 - and it worked (Scala 2.9, Junit4 and Eclipse 3.6)!
They have a great doc here:
http://etorreborre.github.com/specs2/guide/org.specs2.guide.Runners.html#Runners+guide
Since I don't care which testing framework to use, I will try Specs2 purely from the convenience point of view.