Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import or not to import classmethod?

I hope this isn't a stupid question but I found some code where they imported classmethod and some code where they don't so there is difference?

I'm using python 3.6 but the code originally I think was for python 2.7 (it used from __builtin__ import)

import unittest
from selenium import webdriver
from builtins import classmethod #original code was from __builtin__ import classmethod 


class HomePageTest(unittest.TestCase):
    @classmethod
    def setUp(cls):
        # create a new Firefox session
        cls.driver = webdriver.Firefox()
        cls.driver.implicitly_wait(30)
        cls.driver.maximize_window()

        # navigate to the application home page
        cls.driver.get("http://demo-store.seleniumacademy.com/")

    def test_search_field(self):
        pass

    #My tests without @classmethod

    @classmethod
    def tearDown(cls):
        # close the browser window
        cls.driver.quit()

if __name__ == '__main__':
    unittest.main(verbosity=2)
like image 307
fabio Avatar asked Oct 16 '22 08:10

fabio


1 Answers

Normally you only import builtins or __builtin__ if you also have a variable in your code with the same name as a builtin and also want to access the builtin name. The documentation of the module explains it rather well:

builtins — Built-in objects

This module provides direct access to all ‘built-in’ identifiers of Python; for example, builtins.open is the full name for the built-in function open(). See Built-in Functions and Built-in Constants for documentation.

This module is not normally accessed explicitly by most applications, but can be useful in modules that provide objects with the same name as a built-in value, but in which the built-in of that name is also needed. For example, in a module that wants to implement an open() function that wraps the built-in open(), this module can be used directly:

import builtins

def open(path):
    f = builtins.open(path, 'r')
    return UpperCaser(f)

class UpperCaser:
    '''Wrapper around a file that converts output to upper-case.'''

    def __init__(self, f):
        self._f = f

    def read(self, count=-1):
        return self._f.read(count).upper()

However in your case there seems to be no classmethod definition in the file so you don't actually need the from builtins import classmethod.

like image 137
MSeifert Avatar answered Oct 21 '22 00:10

MSeifert