Style Sheets
With PyCharm, you can write style definitions in CSS as well as in various languages that compile into it, such as Sass, Less, SCSS, or Stylus.
You can also look up documentation for Style Sheets, create and move rulesets, introduce variables, and more.
Before you start
Make sure the CSS plugin is enabled in the settings. Press Control+Alt+S to open the IDE settings and then select Plugins . Click the Installed tab. In the search field, type CSS . For more information about plugins, refer to Managing plugins.
Code completion
PyCharm provides code completion for properties, their values, selectors, variables, and mixins.
Complete Style Sheet classes
Completion for CSS, SCSS, Less, and Sass classes and ids is available in HTML files, in various types of templates (for example, in Angular or Vue.js), as well as in JSX code.
In HTML files, PyCharm first suggests classes and ids from the style tag and files linked with link tags. If no matching results are found, PyCharm also suggests symbols defined in all stylesheet files in the project. To see all classes and ids defined in the project straight away, before you start typing, press Control+Space twice.

Complete Style Sheet classes from external libraries
With PyCharm, you can also get completion for class names from Twitter Bootstrap or other CSS libraries that are linked from a CDN in an HTML file without adding these libraries to your project dependencies.
- Open the HTML file with a CDN link to an external CSS library. PyCharm highlights the link.
- To enable completion for the library, press Alt+Enter on the link and select Download library from the list. Alternatively, hover over the link and click Download library .
The library is added to the list of JavaScript libraries on the Settings | Languages and Frameworks | JavaScript | Libraries page. For more information, refer to Configuring a library added via a CDN link.
Complete Sass and SCSS selectors
PyCharm also provides completion for Sass and SCSS selectors — including nested selectors and selectors created with an ampersand (&).

Search and navigation
- To find usages of a Style Sheet symbol, place the caret at it and press Alt+F7 . Learn more from Search for usages in a project.
- To jump from a usage of a Style Sheet symbol to its definition, press Control+B . Navigation to definition is available for classes, ids, selectors – including nested selectors and selectors with an ampersand & — as well as for variables and mixins. Learn more from Go to declaration.
Documentation look-up
For properties and pseudo-elements, PyCharm can show you a summary from the corresponding MDN article. This summary is displayed in the Documentation popup which shows a brief description of the property and its values, as well as information about its compatibility with various browsers.

If the property is available in all versions of browsers, PyCharm does not show any information about its compatibility.
Otherwise, the Documentation popup also lists the browsers and their versions that support the property.
Note that compatibility is checked only for Chrome, Chrome Android, Safari, Safari iOS, Firefox, Internet Explorer, and Edge.
For selectors, PyCharm also shows their specificity.

View documentation for a property
- Position the caret at the property and press Control+Q or select View | Quick Documentation Lookup from the main menu.
- When you hover over a property, PyCharm immediately displays the reference for it in the Documentation popup. You can turn off this behavior or configure the popup to appear faster or slower, refer to Configuring the behavior of Documentation popup below.
Configure the behavior of Documentation popup
- To turn off showing documentation automatically when you hover over code symbols, Click in the popup and disable the Show on Mouse Move option.
- To have the Documentation popup shown faster or slower, open the Settings dialog ( Control+Alt+S ), go to Editor | General | Code Completion , then select the Show the documentation popup checkbox and specify the delay time.
Open the MDN documentation in the browser
- In the Documentation popup Control+Q , click the link at the bottom.
- Press Shift+F1 or select View | External Documentation from the main menu.
Formatting
With PyCharm built-in formatter, you can reformat fragments of Style Sheet code as well as entire files and folders to meet the language-specific code style requirements. The formatter also wakes up automatically when you generate or refactor your code.
- To configure formatting for a Style Sheet language, open the Settings dialog ( Control+Alt+S ), go to Editor | Code Style | Style Sheets | , and configure the language-specific settings for tabs and indents, spaces, wrapping and braces, hard and soft margins, and so on. In the CSS, SCSS, and Less context, PyCharm by default uses double quotes for generated string literals in import statements and URLs. To use single quotes, open the Other tab, and select Single from the Quote marks list. To apply the chosen style to the entire file after reformatting, select the Enforce on format checkbox below the list. Currently changing the configuration for quotation marks does not affect injected style sheets and CSS code inside the tags.
- To reformat a code fragment, select it in the editor and press Control+Alt+L .
- To reformat a file or a folder, select it in the Project tool window and press Control+Alt+L .
Alternatively, you can use the Prettier ( Control+Alt+Shift+P ). For more information, refer to Prettier.
Refactoring
With PyCharm, you can convert expressions in Style Sheets into variables and introduce these variables using the var(—var-name) syntax in .css files or the $ syntax in .scss and .sass files.
Introduce variables
- In the editor, place the caret at the expression to convert into a variable and press Control+Alt+V or select Refactor | Introduce | Introduce Variable from the context menu or from the main menu.
- If more than one occurrence of the selected expression is found, select Replace this occurrence only or Replace all occurrences from the Multiple occurrences found list.
- For .scss , and .sass , select the global or local scope for the variable.
- In the field with red borders, accept the suggested variable name or specify a custom name. Press Enter when ready.
With PyCharm, you can create new rulesets from existing declarations in CSS, SCSS, Sass, or Less files and even move entire rulesets between files using refactoring and intention actions.
Introduce rulesets
- Select the declarations to introduce. If you need only one declaration, just place the caret inside it.
- Press Alt+Enter and select Introduce ruleset from the list.
PyCharm creates a new ruleset with the same selector and moves the selected declarations to it. If the selection contains comments, nested selectors, and so on, they are also moved to the new ruleset.
Move rulesets to other files
- Place the caret anywhere in the ruleset to move and press F6 .
- In the dialog that opens, specify the file to move the ruleset to. If the specified file does not exist, PyCharm will suggest creating it.
- By default, PyCharm automatically opens the file where the ruleset is moved. To change this behavior, clear the Open in editor checkbox.
Common refactorings, such as Copy , Move , or Rename , are also available.
Checking compatibility with browsers
Besides looking up in the documentation popup, you can check Style Sheet properties for compatibility with specific browsers on the fly. This inspection is based on the MDN Browser Compatibility Data and shows you a warning every time a property is not supported in one of the targeted browsers.

Turn on compatibility check

- In the Settings dialog ( Control+Alt+S ), go to Editor | Inspections .
- Expand the CSS node and select the Browser compatibility for properties . In the Options area, select the browsers you want to target and the minimum versions for them.
Changing color values
With PyCharm, you can easily change color values in Style Sheets without typing hexadecimal codes.
Choose colors
- Open the desired Style Sheet for editing.
- Type color: , and then press Control+Space .
- Select the desired color value from the suggestion list or choose color. to pick a custom one.
Change colors
- Open the desired Style Sheet for editing, and locate the color property that you want to change.
- Click the color icon in the gutter. Alternatively, if the icons are not shown, press Alt+Enter and select Change color from the list. See To show color icons in the gutter below.
- In the Choose color dialog that opens, pick the desired new color and click Choose .
Preview the code of colors
- PyCharm marks each color property with a gutter icon of the corresponding color. When you hover over a color icon, PyCharm displays a popup that shows the color preview and its hexadecimal code. To use a code instead of a human-readable color name, press Alt+Enter and select Convert color to from the list, where is HEX, HSL, HWB, or RGB
Show color icons in the gutter
By default, PyCharm displays color icons in the gutter. If they are hidden, you can return them at any time.
- In the Settings dialog ( Control+Alt+S ), go to Editor | General | Gutter Icons . The Gutter Icons page opens.
- In the Common area, select the Color preview checkbox.
Viewing the styles applied to a tag
In HTML and XHTML files, PyCharm can show you all the styles applied to an arbitrary tag.
Здесь определен метод say_hello() , который условно выполняет приветствие — выводит строку на консоль. При определении методов любого класса следует учитывать, что все они должны принимать в качестве первого параметра ссылку на текущий объект, который согласно условностям называется self . Через эту ссылку внутри класса мы можем обратиться к функциональности текущего объекта. Но при самом вызове метода этот параметр не учитывается.
Используя имя объекта, мы можем обратиться к его методам. Для обращения к методам применяется нотация точки — после имени объекта ставится точка и после нее идет вызов метода:
объект.метод([параметры метода])
Например, обращение к методу say_hello() для вывода приветствия на консоль:
tom.say_hello() # Hello
В итоге данная программа выведет на консоль строку «Hello».
Если метод должен принимать другие параметры, то они определяются после параметра self , и при вызове подобного метода для них необходимо передать значения:
class Person: # определение класса Person def say(self, message): # метод print(message) tom = Person() tom.say("Hello METANIT.COM") # Hello METANIT.COM
Здесь определен метод say() . Он принимает два параметра: self и message. И для второго параметра — message при вызове метода необходимо передать значение.
self
Через ключевое слово self можно обращаться внутри класса к функциональности текущего объекта:
self.атрибут # обращение к атрибуту self.метод # обращение к методу
Например, определим два метода в классе Person:
class Person: def say(self, message): print(message) def say_hello(self): self.say("Hello work") # обращаемся к выше определенному методу say tom = Person() tom.say_hello() # Hello work
Здесь в одном методе — say_hello() вызывается другой метод — say() :
self.say("Hello work")
Поскольку метод say() принимает кроме self еще параметры (параметр message), то при вызове метода для этого параметра передается значение.
Причем при вызове метода объекта нам обязательно необходимо использовать слово self , если мы его не используем:
def say_hello(self): say("Hello work") # ! Ошибка
То мы столкнемся с ошибкой
Конструкторы
Для создания объекта класса используется конструктор. Так, выше когда мы создавали объекты класса Person, мы использовали конструктор по умолчанию, который не принимает параметров и который неявно имеют все классы:
tom = Person()
Однако мы можем явным образом определить в классах конструктор с помощью специального метода, который называется __init__() (по два прочерка с каждой стороны). К примеру, изменим класс Person, добавив в него конструктор:
class Person: # конструктор def __init__(self): print("Создание объекта Person") def say_hello(self): print("Hello") tom = Person() # Создание объекта Person tom.say_hello() # Hello
Итак, здесь в коде класса Person определен конструктор и метод say_hello() . В качестве первого параметра конструктор, как и методы, также принимает ссылку на текущий объект — self. Обычно конструкторы применяются для определения действий, которые должны производиться при создании объекта.
Теперь при создании объекта:
tom = Person()
выполняется вызов конструктора __init__() из класса Person, который выведет на консоль строку «Создание объекта Person».
Атрибуты объекта
Атрибуты хранят состояние объекта. Для определения и установки атрибутов внутри класса можно применять слово self . Например, определим следующий класс Person:
class Person: def __init__(self, name): self.name = name # имя человека self.age = 1 # возраст человека tom = Person("Tom") # обращение к атрибутам # получение значений print(tom.name) # Tom print(tom.age) # 1 # изменение значения tom.age = 37 print(tom.age) # 37
Теперь конструктор класса Person принимает еще один параметр — name. Через этот параметр в конструктор будет передаваться имя создаваемого человека.
Внутри конструктора устанавливаются два атрибута — name и age (условно имя и возраст человека):
def __init__(self, name): self.name = name self.age = 1
Атрибуту self.name присваивается значение переменной name. Атрибут age получает значение 1.
Если мы определили в классе конструктор __init__, мы уже не сможем вызвать конструктор по умолчанию. Теперь нам надо вызывать наш явным образом опреледеленный конструктор __init__, в который необходимо передать значение для параметра name:
tom = Person("Tom")
Далее по имени объекта мы можем обращаться к атрибутам объекта — получать и изменять их значения:
print(tom.name) # получение значения атрибута name tom.age = 37 # изменение значения атрибута age
В принципе нам необязательно определять атрибуты внутри класса — Python позволяет сделать это динамически вне кода:
class Person: def __init__(self, name): self.name = name # имя человека self.age = 1 # возраст человека tom = Person("Tom") tom.company = "Microsoft" print(tom.company) # Microsoft
Здесь динамически устанавливается атрибут company, который хранит место работы человека. И после установки мы также можем получить его значение. В то же время подобное определение чревато ошибками. Например, если мы попытаемся обратиться к атрибуту до его определения, то программа сгенерирует ошибку:
tom = Person("Tom") print(tom.company) # ! Ошибка - AttributeError: Person object has no attribute company
Для обращения к атрибутам объекта внутри класса в его методах также применяется слово self:
class Person: def __init__(self, name): self.name = name # имя человека self.age = 1 # возраст человека def display_info(self): print(f"Name: Age: ") tom = Person("Tom") tom.display_info() # Name: Tom Age: 1
Здесь определяется метод display_info(), который выводит информацию на консоль. И для обращения в методе к атрибутам объекта применяется слово self: self.name и self.age
Создание объектов
Выше создавался один объект. Но подобным образом можно создавать и другие объекты класса:
class Person: def __init__(self, name): self.name = name # имя человека self.age = 1 # возраст человека def display_info(self): print(f"Name: Age: ") tom = Person("Tom") tom.age = 37 tom.display_info() # Name: Tom Age: 37 bob = Person("Bob") bob.age = 41 bob.display_info() # Name: Bob Age: 41
Здесь создаются два объекта класса Person: tom и bob. Они соответствуют определению класса Person, имеют одинаковый набор атрибутов и методов, однако их состояние будет отличаться.
При выполнении программы Python динамически будет определять self — он представляет объект, у которого вызывается метод. Например, в строке:
tom.display_info() # Name: Tom Age: 37
Это будет объект tom
bob.display_info()
Это будет объект bob
В итоге мы получим следующий консольный вывод:
Name: Tom Age: 37 Name: Bob Age: 41
Auto import
When you reference a class that has not been imported, PyCharm helps you locate this file and add it to the list of imports. You can import a single class or an entire package, depending on your settings.
The import statement is added to the imports section, but the caret does not move from the current position, and your current editing session does not suspend. This feature is known as the Import Assistant . Using Import Assistant is the preferred way to handle imports in PyCharm because import optimizations are not supported via command line.
The same possibility applies to XML files. When you type a tag with an unbound namespace, the import assistant suggests creating a namespace and offers a list of appropriate choices.
Automatically add import statements
You can configure the IDE to automatically add import statements if there are no options to choose from.
- Press Control+Alt+S to open the IDE settings and then select Editor | General | Auto Import .
- In the Python section, configure automatic imports:
- Select Show import popup to automatically display an import popup when tying the name of a class that lacks an import statement.
- Select one of the Preferred import style options to define the way an import statement to be generated.
Disable import tooltips
When tooltips are disabled, unresolved references are underlined and marked with the red bulb icon . To view the list of suggestions, click this icon (or press Alt+Enter ) and select Import class .
Disable all tooltips
- Hover over the inspection widget in the top-right corner of the editor, click , and disable the Show Auto-Import Tooltip option.
Disable auto import
If you want to completely disable auto-import, make sure that:
- All import tooltips are disabled.
- The automatic insertion of import statements is disabled.
Optimize imports
The Optimize Imports feature helps you remove unused imports and organize import statements in the current file or in all files in a directory at once according to the rules specified in Settings | Editor | Code Style | | Imports .
You can exclude specific files and folders from import optimization. For more information, refer to Exclude files from reformatting.
Optimize all imports
- Select a file or a directory in the Project tool window ( View | Tool Windows | Project ).
- Do any of the following:
- Go to Code | Optimize Imports (or press Control+Alt+O ).
- From the context menu, select Optimize Imports .
- (If you’ve selected a directory) Choose whether you want to optimize imports in all files in the directory, or only in locally modified files (if your project is under version control), and click Run .
Optimize imports in a single file

- Place the caret at the import statement and press Alt+Enter or use the icon.
- Select Optimize imports .
To optimize imports in a file, you can also press Control+Alt+Shift+L , select Optimize imports , and click Run .
Optimize imports when committing changes to Git
If your project is under version control, you can instruct PyCharm to optimize imports in modified files before committing them to VCS.

- Press Control+K or select Git | Commit from the main menu.
- Click and in the commit message area, select the Optimize imports checkbox.
Automatically optimize imports on save
You can configure the IDE to optimize imports in modified files automatically when your changes are saved.
- Press Control+Alt+S to open the IDE settings and then select Tools | Actions on Save .
- Enable the Optimize imports option. Additionally, from the All file types list, select the types of files in which you want to optimize imports.
- Apply the changes and close the dialog.
Optimize imports when reformatting a file
You can tell PyCharm to optimize imports in a file every time it is reformatted.

- Open the file in the editor, press Control+Alt+Shift+L , and make sure the Optimize imports checkbox is selected in the Reformat File dialog that opens.
After that every time you press Control+Alt+L in this project, PyCharm will optimize its imports automatically.
Creating imports on the fly
Import packages on-the-fly
- Start typing a name in the editor. If the name references a class that has not been imported, the following prompt appears:
The unresolved references will be underlined, and you will have to invoke intention action Add import explicitly. - Press Alt+Enter . If there are multiple choices, select the desired import from the list.

You can define your preferred import style for Python code by using the following options available on the Auto Import page of the project settings ( Settings | Editor | General | Auto Import ):
PyCharm provides a quick-fix that automatically installs the package you’re trying to import: if, after the keyword import , you type a name of a package that is not currently available on your machine, a quick-fix suggests to either ignore the unresolved reference, or download and install the missing package:

Toggling relative and absolute imports
PyCharm helps you organize relative and absolute imports within a source root. With the specific intention, you can convert absolute imports into relative and relative imports into absolute.
If your code contains any relative import statement, PyCharm will add relative imports when fixing the missing imports.
Note that relative imports work only within the current source root: you cannot relatively import a package from another source root.
The intentions prompting you to convert imports are enabled by default. To disable them, open project Settings ( Control+Alt+S ), select Editor | Intentions , and deselect the Convert absolute import to relative and Convert relative import to absolute .

When you complete a ES6 symbol or a CommonJS module, PyCharm either decides on the style of the import statement itself or displays a popup where you can choose the style you need. Learn more from Auto-import in JavaScript.
Adding import statements on code completion
PyCharm automatically adds an import statement when you refer any module member or package in the Python code and invoke code completion. Auto-import on code completion is also applied to some popular package name aliases, such as np for numpy or pd for pandas .
PyCharm also adds import statements when you complete exported JavaScript or TypeScript symbols.
Configure auto-import on completion
You can disable auto-import on completion and use quick-fixes instead:
- In the Settings dialog ( Control+Alt+S ), go to Editor | General | Auto Import .
- On the Auto Import page that opens, use the checkboxes in the TypeScript/JavaScript area to enable or disable import generation on code completion.
Ignoring missing import statements
If you use a module in your code that doesn’t have any corresponding stub, PyCharm might show a missing statement error. To suppress this error message, use the # type: ignore comment:
Не получается импортировать класс

Привет. У меня есть класс CStatistics , который необходимо импортировать. Данный класс находится по адресу: DataUnloader/Statistic/CStatistics.py Скрипт, в который должен произойти импорт находится по адресу: ./ (на скрине Quality ) Чтобы было понятнее, я прикреплю скрин: Проблема в том, что указанный класс не подцепляется. Логично, что нужно сделать так:
import DataUnloader.Statistic.SStatistics

чтобы его подцепить. Но это не помогает Здесь задавался подобный вопрос. Он совпадает с моим мнением. Но это не помогло решить проблему. Подскажите, как сделать импорт? PyCharm , в котором я веду разработку, не хочет даже видеть DataUnloader :
Отслеживать
задан 6 апр 2017 в 11:32
hedgehogues hedgehogues
9,491 9 9 золотых знаков 50 50 серебряных знаков 103 103 бронзовых знака
Эм. У вас в папке лежит «CStatistics» а вы импортируете «SStatistics»
6 апр 2017 в 12:12
@Alban Пардон, в скрине ошибка. Но факт в том, что даже DataUnloader он не видит.
6 апр 2017 в 12:26
@Alban что он сделает?
6 апр 2017 в 12:44
2 ответа 2
Сортировка: Сброс на вариант по умолчанию
во-первых, в PyCharm можно помечать директорию как source root, что позволяет ему видеть директории ниже
во-вторых, я не вижу в Вашей иерархии __init__.py -файлов, они нужны, чтобы Python и PyCharm знали, что это не просто директория, а пакет с модулями, без них импорт не сработает как нужно
Отслеживать
ответ дан 6 апр 2017 в 14:14
Azat Ibrakov Azat Ibrakov
196 6 6 бронзовых знаков
Используйте следующею конструкцию:
import sys sys.path.append(r"/путь/к/каталогу/в/котором/лежит/модуль") import name # Где name название модуля в этом каталоге
К примеру есть python файл в который вам необходимо импортировать модуль под названием My_class .
Python file лежит на рабочем столе. Модуль также на рабочем толе, но по пути: /test/test_2/ и содержит в себе следующее:
def check(): print('Im here!')
import sys sys.path.append(r"C:\Users\user\Desktop\test\test_2") import My_class My_class.check() # Проверяем
Видим что всё работает:
Im here!