How can I tell PyCharm what type a parameter is expected to be?
Yes, you can use special documentation format for methods and their parameters so that PyCharm can know the type. Recent PyCharm version supports most common doc formats.
For example, PyCharm extracts types from @param style comments.
See also reStructuredText and docstring conventions (PEP 257).
Another option is Python 3 annotations.
Please refer to the PyCharm documentation section for more details and samples.
Is there a way to explicitly tell PyCharm what class an attribute is an instance of?
Actually PyCharm also understands the 'assert isinstance' syntax, but only for unqualified references. I've filed an issue to support this for qualified references as well:
http://youtrack.jetbrains.net/issue/PY-5614
In the current version, you can specify the type of my_attribute by going to the declaration of SomeClass and adding a epydoc or sphinx docstring for the attribute.
Pycharm type hints warning for classes instead of instances
When you are doing print_greeting(HelloGreetingMaker, "John")
, you are not trying to pass in an instance of HelloGreetingMaker. Rather, you're passing in the class itself.
The way we type this is by using Type[T]
, which specifies you want the type of T, rather then an instance of T. So for example:
from typing import Type
import abc
class GreetingMakerBase(abc.ABC):
@staticmethod
@abc.abstractmethod
def make_greeting(name: str) -> str:
""" Makes greeting string with name of person """
class HelloGreetingMaker(GreetingMakerBase):
@staticmethod
def make_greeting(name: str) -> str:
return "Hello {}!".format(name)
def print_greeting(maker: Type[GreetingMakerBase], name):
print(maker.make_greeting(name))
# Type checks!
print_greeting(HelloGreetingMaker, "John")
Note that Type[HelloGreetingMaker]
is considered to be compatible with Type[GreetingMakerBase]
-- Type[T]
is covariant with respect to T.The Python docs on the typing module and the mypy docs have more details and examples if you want to learn more.
How to specify that a parameter is a list of specific objects in Python docstrings
In comments section of PyCharm's manual there's a nice hint from developer:
#: :type: dict of (str, C)
#: :type: list of str
It works for me pretty well. Now it makes me wonder what's the best way to document parametrized classes in Python :). How can I tell PyCharm that an object is a specialization (subclass) of a type without using isinstance?
You could give additional type hints to PyCharm
def dispatch():
item = get_item()
item_type = type(item)
if item_type is Subtype1:
item: Subtype1
receiver1(item)
elif item_type is Subtype2:
item: Subtype2
receiver2(item)
This should not affect performance of the code.Another approach would be to inject the receiver method into Subtype1/2 classes:
def receiver1(arg: Subtype1):
print("receiver1 called")
def receiver2(arg: Subtype2):
print("receiver2 called")
class MyMeta(type):
pass
d = dict(Subtype1.__dict__)
d.update({"receiver": receiver1})
Subtype1 = MyMeta(Subtype1.__name__,
Subtype1.__bases__,
d)
d = dict(Subtype2.__dict__)
d.update({"receiver": receiver2})
Subtype2 = MyMeta(Subtype2.__name__,
Subtype2.__bases__,
d)
def dispatch():
item = get_item()
item.receiver()
PyCharm TensorFlow warning - Type 'Variable' doesn't have expected attribute '__sub__'
The -
operator is called on var
inside variable_summaries
:
stddev = tf.sqrt(tf.reduce_mean(tf.square(var - mean)))
Normally Python would be looking for the __sub__
method of var
when evaluating the expression var - mean
. However, a tf.Variable
instance is wrapped around state_ops.variable_op_v2
in order to support Ops on GPU/CPU and does not have a __sub__
method that Python would normally expect.
Therefore, this warning is inherent to the way TensorFlow heavily customizing standard Python operators on Tensorflow objects in order to support the expressions we are used to while enabling GPU/CPU computation with Tensorflow OPs.
I'd say you can safely ignore this warning on any Tensorflow object. Unfortunately I don't know how you can suppress this warning in PyCharm.
How to define a type hint to a argument (the argument's value is a class, all expected value is a subclass of a certain class)?
If you are trying to say that arg
must be an instance of either MyClass
or some subtype of MyClass
, just do this:
class MyClass(object): pass
class Child(MyClass): pass
def my_function(arg: MyClass) -> None:
pass
my_function(MyClass()) # Type checks
my_function(Child()) # Type checks
my_function(3.14) # Does not type check
If you are trying to say that arg
must be literally the MyClass
class object or a subtype, use typing.Type
:from typing import Type
# ...snip...
def my_function_2(arg: Type[MyClass]) -> None:
pass
my_function_2(MyClass) # Type checks
my_function_2(Child) # Type checks
my_function_2(int) # Does not type check
my_function_2(MyClass()) # Does not type check
Of course, the type checker won't be able to tell exactly which subtype you happen to be using within the functions themselves.This is actually not something you can do. It is impossible to construct a type hint that asserts some value must be exactly one type and never any subtypes of that type (though you can often simulate something close-ish by using generics).the type hint can only help when requiring value is a instance of certain type.
A type hint always indicates that some value is either an instance of that type or some subtype.
You may find reading the mypy docs to be useful, if you haven't found them already.And the relevant documentation is really poor.
Mypy is a PEP 484 compliant static type checker, and was developed in parallel with PEP 484 itself. (E.g. the core mypy devs were the ones who wrote PEP 484 and several other typing-related PEPs.)
The upshot is that the docs for mypy are generally more helpful than the official Python docs for typing.
Is there a way to view parameter information in the PyCharm console?
It's a known issue, please vote for https://youtrack.jetbrains.com/issue/PY-36610
Related Topics
Hide Chromedriver Console in Python
Runtimeerror: This Event Loop Is Already Running in Python
What Does Model.Train() Do in Pytorch
Adding a Y-Axis Label to Secondary Y-Axis in Matplotlib
Cartesian Product of a Dictionary of Lists
Python & Pandas: How to Query If a List-Type Column Contains Something
Use Index in Pandas to Plot Data
Slicing of a Numpy 2D Array, or How to Extract an Mxm Submatrix from an Nxn Array (N>M)
Numpy Array Dtype Is Coming as Int32 by Default in a Windows 10 64 Bit MAChine
Why "Numpy.Any" Has No Short-Circuit Mechanism
What's the Best Way to Store a Phone Number in Django Models
Multiprocessing:Use Tqdm to Display a Progress Bar
How to Get the Version Defined in Setup.Py (Setuptools) in My Package
Pandas Dataframe Aggregate Function Using Multiple Columns
How to Write a Generator Class
Find Index of Last Occurrence of a Substring in a String