Exemplo n.º 1
0
def string_interpolation():
    value1 = 1
    value2 = 2
    value3 = 3  # Noncompliant
    value4 = 4  # Noncompliant (previously FN)
    value5 = 1
    foo(F'{value5} foo')
    value6 = ''  # Noncompliant FP
    print(f"{'}' + value6}")
    return f'{value1}, {2*value2}, value3bis, value4'
Exemplo n.º 2
0
def using_tuples():
    x, y = (1, 2)
    print x
    (a, b) = (1, 2)
    print b

    for name, b in foo():
        pass
    for (c, d) in foo():
        pass
Exemplo n.º 3
0
def string_interpolation():
    value1 = 1
    value2 = 2
    value3 = 3 # Noncompliant
    value4 = 4 # Noncompliant
    value5 = 1
    foo(F'{value5} foo')
    value6 = ''
    print(f"{'}' + value6}")
    value7 = ''
    printf(rf'{value7}')
    return f'{value1}, {2*value2}, value3bis, value4'
Exemplo n.º 4
0
def string_interpolation():
    value1 = 1
    value2 = 2
    value3 = 3  # Noncompliant
    value4 = 4  # Noncompliant
    value5 = 1
    foo(F'{value5} foo')
    value6 = ''
    print(f"{'}' + value6}")
    value7 = ''
    printf(rf'{value7}')
    value8 = 10
    value9 = 10
    print(f"{3.14159265358979:{value8}.{value9 * 5}}")
    return f'{value1}, {2*value2}, value3bis, value4'
    def test_override_builtin(self):
        # Test that overriding builtins.__import__ can bypass sys.modules.
        import os

        def foo():
            import os
            return os
        self.assertEqual(foo(), os)  # Quick sanity check.

        with swap_attr(builtins, "__import__", lambda *x: 5):
            self.assertEqual(foo(), 5)

        # Test what happens when we shadow __import__ in globals(); this
        # currently does not impact the import process, but if this changes,
        # other code will need to change, so keep this test as a tripwire.
        with swap_item(globals(), "__import__", lambda *x: 5):
            self.assertEqual(foo(), os)
Exemplo n.º 6
0
    def test_override_builtin(self):
        # Test that overriding builtins.__import__ can bypass sys.modules.
        import os

        def foo():
            import os
            return os
        self.assertEqual(foo(), os)  # Quick sanity check.

        with swap_attr(builtins, "__import__", lambda *x: 5):
            self.assertEqual(foo(), 5)

        # Test what happens when we shadow __import__ in globals(); this
        # currently does not impact the import process, but if this changes,
        # other code will need to change, so keep this test as a tripwire.
        with swap_item(globals(), "__import__", lambda *x: 5):
            self.assertEqual(foo(), os)
Exemplo n.º 7
0
    # actually a new local!
    global_ = "local"
    # actually not a new local but imported one?
    imported = "imported"
    return local
    return param1
    return imported


def foo2():
    global global_
    # now it references the global
    global_ = "global2"
    return global_


def foo3(x, y):
    def bar(x):
        nonlocal y
        return x + y

    yield bar(x)


print(foo.imported)
print(global_)
foo(1, 2)
print(global_)
foo2()
print(global_)
Exemplo n.º 8
0
 def testCallFunc(self):
     foo(bar)
     foo(bar=None)
     foo(bar, moo=None)
     foo(boo, *args)
     foo(boo, *args, **kwargs)
Exemplo n.º 9
0
 def test(self):
     response = foo()
     self.assertEqual(200, response.status_code)
     self.assertEqual(b'Hello World', response.content)
Exemplo n.º 10
0
	def foo(x):
		print x
		print y # Sunaba と違ってグローバル変数を関数内で使ってもいい

# --- リストも渡せる ---
	def sum_list(a):
		total = 0
		for b in a:
			total += b
		return total
	print sum_list([1, 2, 3]) # 6

# --- デフォルト引数 ---
	def foo(a, b = 10, c = 'c'):
		print a, b, c
	foo(1) # 1, 10, c が出る

# --- キーワード引数 ---
	def foo(a, b = 10, c = 'c'):
		print a, b, c
	foo(1, c = 'しい', b = 2)
	# 順番があべこべでもOK
	def bar(a, b = 10, **c):
		print a, b, c
	bar(1, b = 20, d = 20, e = 40) # {'d': 20, 'e': 40}ってのが出てくる

# --- ディクショナリを展開して関数に渡す ---
	dic1 = {'a': 10, 'b': 20}
	def foo(a = 1, b = 2):
		print a, b
	print foo(**dic1) # 10, 20 が出てくる
Exemplo n.º 11
0
#/usr/bin/python3
#
#module

print("=" * 100)
print("6.1 Module")
print("=" * 100)
import foo
foo.foo(200)
print(foo.__name__)

#import other way
#or from foo import * will import all functions except the function which name start with _
#from foo import foo
from foo import *
foo(50)
#can't access _xxx function
#_test()
#foo._test()

#or rename
from foo import foo as foo1
foo1('This is foo1')

#if using interative mode, the module only import once, or use importlib.reload(modulename)。
Exemplo n.º 12
0
ИМПОРТЫ СОРТИРУЮТСЯ ЛЕКСИКОГРАФИЧЕСКИ регистроЗАВИСИМО СОГЛАСНО ПОЛНОМУ ПУТИ МОДУЛЯ
    import foo
    from foo import bar
    from foo.bar import baz
    from foo.bar import Quux
    from Foob import ar


КОНСТРУКЦИЯ НА ОДНОЙ СТРОКЕ ТОЛЬКО IF EXP НЕ СОСТАВНОЕ
    if foo: bar(foo)
    
    if foo:
        bar(foo)
    else:
        foo(bar)


?КОНТРОЛЬ ДОСТУПА
#if геттер был бы простым, я должен был бы использовать общедоступные v для геттеров для избежания дополнительных расходов на внутренние вызовы p. if добавлено много фунциональности, можно исп св-ва, чтобы следовать целосности интерфейса. С одной стороны if геттер более сложна|скорость доступа к v важна -> можно использовать вызовы Fx(такие как get_foo(), set_foo()). If поведение позволяет доступ через св-во - не привязывай к нему новый геттер. Любой код, который все еще пытается получить доступ к v с помощью старого метода, должен явно падать чтобы я увидел что сложность доступа изменилась



ИМЕНОВАНИЕ
    module_name, package_name
    ClassName
    method_name
    ExceptionName
    function_name
    GLOBAL_CONSTANT
    global_variable
    instance_var
    function_parameter
Exemplo n.º 13
0
 def test(self):
     response = foo()
     self.assertEqual(True, foo())
Exemplo n.º 14
0
import requests

x = requests.get('http://foo.com/users')
x.json()

#----------------------------------------
while x != 3:
    print(x)
    x = x + 1

#---------------------------------------- function
def foo(x, y):
    print(x,y)
    return x

foo(123) # calling the function
#---------------------------------------- files

x = open(foo.txt, 'w')  # 'w'  'r' 'a'
x.write('hello\n')
x.write('brian\n')
x.close()

x = open('foo.txt', 'r')
print(x.read())  # .readline()
x.close()

#----------------------------------------
x = []
x.append(1)
x.append(2)
Exemplo n.º 15
0
from foo import *
import bar

print('Вызываю foo(x) от 10')
foo(10)

print('Вызываю bar(x) от 100 = ' + str(bar.bar(100)))

Exemplo n.º 16
0
 def test(self):
     response = foo()
     self.assertEqual(200, response.status_code)
     self.assertEqual(b'Hello World', response.content)
Exemplo n.º 17
0
## subn
re.subn('a', 'b', 'c')
re.subn('a', 'b', 'c', 0)
re.subn('a', 'b', 'c', 0, re.IGNORECASE)
re.subn('a', 'b', 'c', flags=re.IGNORECASE)
re.subn('a', 'b', 'c', count=0, flags=re.IGNORECASE)

## escape
re.escape('a')

# Goofy verbose (X) example from python docs
re.compile(
    r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)

# Try with lots of flags
re.compile('[a-z]+', re.IGNORECASE | re.MULTILINE)
re.compile('[a-z]+', re.IGNORECASE | re.MULTILINE | re.DOTALL)

# More complex calls
## Nesting -- should be <nestedOnce, 'DYNAMIC-FLAGS'> and <nestedTwice, ''>
foo(
    re.match('nestedOnce', 'b',
             re.IGNORECASE if re.match('nestedTwice', 'd') else re.IGNORECASE))
## Partially-dynamic flags
re.compile('partiallyDynamicFlags-[a-z]+', re.IGNORECASE | foo(re.MULTILINE))
## Numeric flags
re.subn('a', 'b', flags=0)
re.subn('a', 'b', flags=0 | re.IGNORECASE)
Exemplo n.º 18
0
from foo import (
foo
foo
)

code = 1

from foo import (
foo
foo
foo
)

code = 1

import foo; foo()
import foo
import foo
import foo

code = 1

from foo import \
        bar

code = 1

from foo import \
bar             \
bar
Exemplo n.º 19
0
def funcs():
    foo(1)
    foo(1, 2)
    foo(1, 2, 3)
Exemplo n.º 20
0
 def testCallFunc(self):
     foo(bar)
     foo(bar=None)
     foo(bar, moo=None)
     foo(boo, *args)
     foo(boo, *args, **kwargs)
Exemplo n.º 21
0
def bar():
    if(1 == 2):
        return 0
    if(1+2 == 1+2):
        return 1
    if(1+2 == 1+2):
        foo()
    if(x == x):
        foo()
        bar()
    if(True)
        foo()
    foo()    
    if(True)
        foo()
        foo()
Exemplo n.º 22
0
#! coding: cp1252

import foo
import bar

foo("""
"Alors vous imaginez ma surprise, au lever du jour, quand "
                "une drôle de petite voix m’a réveillé. Elle disait: "
                "« S’il vous plaît… dessine-moi un mouton! »"

""")

bar()
Exemplo n.º 23
0
 def test_something(self):
     # print(type(self))
     self.assertEqual(True, False)
     foo()  # understading __name__ == '__main__'